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:
a for b, a ...-> display the valuesa for a, a ...-> display the valuesa for a, b ...-> display the keysa for b, b ...-> display the last key
Can anyone elaborate the flow of the loop for every case above?
The list comprehension you use there roughly translate as follows:
becomes
becomes
becomes
becomes
This last one is special. It only worked because you had used the variable
ain a previous statement, and the last value that had been assigned to it was3. If you execute this statement first, you’d get an error.