0

I read this particular thread on Stack Overflow, but I'm still wondering... why doesn't variable swapping work if you put the tuple in a function, like so:

def badswap(x,y):
   x,y = y,x

badswap(a,b)

I saw this particular example in How to Think Like a Computer Scientist and have been dwelling over this issue ever since.

Any shedding of light here would be much much appreciated.

-T

Community
  • 1
  • 1
Toddsqui
  • 59
  • 2
  • 10

1 Answers1

0

Because you're only rebinding the local names; the actual objects and names will be unchanged outside the function.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Ooh, so you're saying that a and b will ONLY change inside the function, not outside of it?? Okay, that makes sense to me, but then how could we extract the switch outside of the function? In other words, how could we globalize the variables?? – Toddsqui Apr 15 '15 at 11:30
  • There is no sane way to do so. You'd have to walk the scopes, figure out what the function was called with, and attempt to swap those. But don't do that. – Ignacio Vazquez-Abrams Apr 15 '15 at 14:19