Assign Many Variables at Once, Python

你离开我真会死。 提交于 2019-12-02 06:23:12

No need to use tuple assignment here; the right-hand value is immutable, so you can just as well share the reference:

a = b = c = 'yyy'

This is not unintuitive at all, in my view, and the python compiler will only need to store one constant with the bytecode, while using tuple assignment requires an additional tuple constant:

>>> def foo():
...     a, b, c = 'yyy', 'yyy', 'yyy'
... 
>>> foo.__code__.co_consts
(None, 'yyy', ('yyy', 'yyy', 'yyy'))
>>> def bar():
...     a = b = c = 'yyy'
... 
>>> bar.__code__.co_consts
(None, 'yyy')

Don't use this if the right-hand expression is mutable and you want a, b and c to have independent objects; use a generator expression then:

a, b, c = ({} for _ in range(3))

or better still, don't be so lazy and just type them out:

a, b, c = {}, {}, {}

It's not as if your left-hand assignment is dynamic.

>>> a, b, c = ("yyy",)*3 

The above construct is equivalent to a = b = c = "yyy" but requires creation of a tuple in memory, and still a,b,c are just references to the same object.

For different id's use:

a, b, c = ("yyy" for _ in xrange(3))

This will not matter for string as they are immutable, but for mutable object they are different type of assignments.

>>> a = b = c = []       #all of them are references to the same object
>>> a is b
True
>>> a.append(1)          #Modifying one of them in-place affects others as well
>>> a, b, c
([1], [1], [1])
>>> a, b, c, = ([],)*3   #same as a = b = c = []
>>> a is b
True

#Here a, b, c point to different objects
>>> a, b, c, = ([] for _ in xrange(3))
>>> a is b
False
>>> a.append(1)
>>> a, b, c
([1], [], [])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!