1

Is there a better way to do this?

a, b, c, = "yyy", "yyy", "yyy"

Obvious attempts fails

a, b, c, = "yyy"
a, b, c = "yyy"*3

Technically, the following works, but I don't think it's intuitive as this logic says a, b, and c are the same, whereas all I'm trying to do is say they initialize as the same value

a=b=c="yyy"
appleLover
  • 14,835
  • 9
  • 33
  • 50
  • *"... this logic says a, b, and c are the same ..."* No, that would be `a == "yyy" and b == "yyy" and c == "yyy"`. `=` is assignment, never equality. – cdhowie Sep 06 '13 at 16:01

2 Answers2

11

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5
>>> 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], [], [])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504