Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lack Understanding of Multi-Variable Assignments Python

I'm new with Python (with Java as a basic). I read Dive Into Python books, in the Chapter 3 I found about Multi-Variable Assignment. Maybe some of you can help me to understand what happen in this code bellow:

>>> params = {1:'a', 2:'b', 3:'c'}
>>> params.items() # To display list of tuples of the form (key, value).
[(1, 'a'), (2, 'b'), (3, 'c')]

>>> [a for b, a in params.items()] #1
['a', 'b', 'c']
>>> [a for a, a in params.items()] #2
['a', 'b', 'c']
>>> [a for a, b in params.items()] #3
[ 1 ,  2 ,  3 ]
>>> [a for b, b in params.items()] #4
[ 3 ,  3 ,  3 ]

What I understand so far is the #1 and #2 has same output, that display the values of tuple. #3 display the key of tuple, and #4 just display the last key from the list of tuples.

I don't understand the use of the variable a and variable b for every case above:

  1. a for b, a ... -> display the values
  2. a for a, a ... -> display the values
  3. a for a, b ... -> display the keys
  4. a for b, b ... -> display the last key

Can anyone elaborate the flow of the loop for every case above?

like image 789
Crazenezz Avatar asked Aug 03 '12 07:08

Crazenezz


1 Answers

The list comprehension you use there roughly translate as follows:

[a for b, a in params.items()]

becomes

result = []
for item in params.items():
    b = item[0]
    a = item[1]
    result.append(a)

[a for a, a in params.items()]

becomes

result = []
for item in params.items():
    a = item[0]
    a = item[1] # overwrites previous value of a, hence this yields values, 
                # not keys
    result.append(a)

[a for a, b in params.items()]

becomes

result = []
for item in params.items():
    a = item[0]
    b = item[1]
    result.append(a)

[a for b, b in params.items()]

becomes

result = []
for item in params.items():
    b = item[0]
    b = item[1]
    result.append(a) # note use of a here, which was not assigned

This last one is special. It only worked because you had used the variable a in a previous statement, and the last value that had been assigned to it was 3. If you execute this statement first, you'd get an error.

like image 101
Björn Pollex Avatar answered Nov 15 '22 00:11

Björn Pollex