I really thought I understood Python variable referencing, so I’m confused why this code isn’t making the variable “a” be “1”:
>>> a,b,c = None, None, None
>>> for var, val in zip((a,b,c),[1]):
... var = val
...
>>> print a
None
>>> print var
1
Can anyone explain what Python is doing here? Why don’t “var” and “a” point to the same place?
Bonus question: What’s an elegant way to assign three variables from a list that can have 1-3 items and leave the variables set to None if the list falls short?
It’s assigning the value of the variable
valto the variablevar. It is not changinga. Try the following to see what is happening:zipnever sees the variablesa,bandc, just the values they are bound to.Read up on Python’s use of variables (names, really) in Code Like a Pythonista.
Don’t construct variables dynamically. Use a list instead.
Then use
vars[0]etc. Or