Question

I am reading a book about Python and there is a special part in the book about Multiple-Target Assignments. Now the book explains it like this:

enter image description here

but I dont see use of this. This makes no sense for me. Why would you use more variables? Is there a reason to do this? What makes this so different from using: a='spam'and then printing out a 3 times?

I can only think of using it for emptying variables in one line.

Was it helpful?

Solution

A very good use for multiple assignment is setting a bunch of variables to the same number.

Below is a demonstration:

>>> vowels = consonants = total = 0
>>> mystr = "abcdefghi"
>>> for char in mystr:
...     if char in "aeiou":
...         vowels += 1
...     elif char in "bcdfghjklmnpqrstvwxyz":
...         consonants += 1
...     total += 1
...
>>> print "Vowels: {}\nConsonants: {}\nTotal: {}".format(vowels, consonants, total)
Vowels: 3
Consonants: 6
Total: 9
>>>

Without multiple assignment, I'd have to do this:

>>> vowels = 0
>>> consonants = 0
>>> total = 0

As you can see, this is a lot more long-winded.

Summed up, multiple assignment is just Python syntax sugar to make things easier/cleaner.

OTHER TIPS

It's mainly just for convenience. If you want to initialize a bunch of variables, it's more convenient to do them all on one line than several. The book even mentions that at the end of the snippet that you quoted: "for example, when initializing a set of counters to zero".

Besides that, though, the book is actually wrong. The example shown

a = b = c = 'spam'

is NOT equivalent to

c = 'spam'
b = c
a = b

What it REALLY does is basically

tmp = 'spam'
a = tmp
b = tmp
c = tmp
del tmp

Notice the order of the assignments! This makes a difference when some of the targets depend on each other. For example,

>>> x = [3, 5, 7]
>>> a = 1
>>> a = x[a] = 2
>>> a
2
>>> x
[3, 5, 2]

According to the book, x[1] would become 2, but clearly this is not the case.

For further reading, see these previous Stack Overflow questions:

How do chained assignments work?

What is this kind of assignment in Python called? a = b = True

Python - are there advantages/disadvantages to assignment statements with multiple (target list "=") groups?

And probably several others (check out the links on the right sidebar).

You might need to initialize several variables with the same value, but then use them differently. It could be for something like this:

def fibonacci(n):
    a = b = 1
    while a < n:
        c = a
        a = a + b
        b = c
    return a

(variable swapping with tuple unpacking ommited to avoid confusion as with the downvoted answer)

An important note:

>>> a = b = []

is dangerous. It probably doesn't do what you think it does.

>>> b.append(7)
>>> print(b)
[7]
>>> print(a)
[7]           # ???????

This is due to how variables work as names, or labels, in Python, rather than containers of values in other languages. See this answer for a full explanation.

Presumably you go on to do something else with the different variables.

a = do_something_with(a)
b = do_something_else_with(b)
#c is still 'spam'

Trivial example and the initialization step questionably didn't save you any work, but it's a valid way to code. There are certainly places where initializing a significant number of variables is needed, and as long as they're immutable this idiom can save space.

Though as the book pointed out, you can only use this type of grammar for immutable types. For mutable types you need to explicitly create multiple objects:

a,b,c = [mutable_type() for _ in range(3)]

Otherwise you end up with surprising results since you have three references to the same object rather than three objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top