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 keyCan anyone elaborate the flow of the loop for every case above?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With