1

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Loko
  • 6,539
  • 14
  • 50
  • 78
  • @aIKid In what situation would you need 3 strings with the same word? – Loko Dec 11 '13 at 15:55
  • The book is (slightly) wrong. See my answer. In case anyone is wondering, this is from Mark Lutz's famous *Learning Python*. Still a lot of useful information in the book for Python learners. – John Y Dec 11 '13 at 16:12

4 Answers4

6

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.

  • Aha pretty good answer. This could change a loop. Good thinking! – Loko Dec 11 '13 at 15:50
  • The case where one assignment target involves destructuring and the other doesn't also seems like a reasonably common use case: `x, y = p = compute_2d_vector()` – svk Dec 11 '13 at 15:51
  • Yep, multiple assigments is just a syntax sugar. Nice explanation! – aIKid Dec 11 '13 at 15:52
  • About the last part, I know it's for making it easier/cleaner but I couldn't think of a logical situation to use this. – Loko Dec 11 '13 at 15:52
  • @iCodez: Are you going to cv this as too broad? – aIKid Dec 11 '13 at 15:53
  • @iCodez sorry if this is too broad but at the time I couldn't think of any logical reason to use 3 variables like that – Loko Dec 11 '13 at 15:58
  • @aIKid - You know, now that I think about it, I see a ton of questions like this on SO. In fact, some of the best/most famous are people simply saying "what the heck does this do?". I changed my mind -- I'll leave it and let others close it if they want. –  Dec 11 '13 at 16:08
3

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).

Community
  • 1
  • 1
John Y
  • 14,123
  • 2
  • 48
  • 72
1

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.

Community
  • 1
  • 1
rlms
  • 10,650
  • 8
  • 44
  • 61
0

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.

Community
  • 1
  • 1
roippi
  • 25,533
  • 4
  • 48
  • 73