Multiple Assignment Semantics

In Python, you can do:

a, b = 1, 2 (a, b) = 1, 2 [a, b] = 1, 2 

I checked the generated bytecode with dis and they are identical.
So why bother with this? Will I ever have one of them instead of the rest?

+61
python variable-assignment
Mar 03 2018-11-11T00:
source share
5 answers

One case where you need to include more structure on the left side of the job is when you ask Python to unpack a slightly more complex sequence. For example:.

 # Works >>> a, (b, c) = [1, [2, 3]] # Does not work >>> a, b, c = [1, [2, 3]] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: need more than 2 values to unpack 

This has proved useful to me in the past, for example, when using an enumeration to iterate over a sequence of 2 tuples. Something like:

 >>> d = { 'a': 'x', 'b': 'y', 'c': 'z' } >>> for i, (key, value) in enumerate(d.iteritems()): ... print (i, key, value) (0, 'a', 'x') (1, 'c', 'z') (2, 'b', 'y') 
+66
Mar 03 2018-11-11T00:
source share

Python tuples can often be written with or without parentheses:

 a = 1, 2, 3 

equivalently

 a = (1, 2, 3) 

In some cases, you need parentheses to disambiguate, for example, if you want to pass a tuple (1, 2) to a function f , you need to write f((1, 2)) . Since brackets are sometimes needed, they are always allowed for consistency, just as you can always write (a + b) instead of a + b .

If you want to unzip a nested sequence, you also need parentheses:

 a, (b, c) = 1, (2, 3) 

There seems to be no reason to use square brackets as well, and people rarely do.

+10
Mar 03 2018-11-11T00:
source share

They are also the same, because the assignment occurs from right to left and right, you have one type, which is a sequence of two elements. When a call is assigned, the sequence is unpacked and looks for the corresponding elements that match and are given to these values. Yes, any method should be good in this case, when the sequence is unpacked into the corresponding elements.

+1
Mar 03 2018-11-11T00:
source share

An open bracket allows you to assign multi-line strings. For example, when reading a line from csv.reader() it makes the code more readable (if less efficient) for loading the list into named variables with one assignment.

Starting with a bracket, avoids long or \ escaped strings.

(a, b, c) = [1, 2, 3]

(Imagine more and more variable names)

0
Jun 29 '17 at 0:05
source share

When unpacking a singleton iterable list syntax is better:

 a,=f() # comma looks out of place (a,)=f() # still odd [a]=f() # looks like every other list 
0
Jan 05 '18 at 20:48
source share



All Articles