[Tutor] Re: tuple/list assignment in 'for-in'

Brian Beck exogen at gmail.com
Wed Apr 27 10:10:21 CEST 2005


brian will wrote:
> Hi there,
> 
> I can't explain my experience with what I like to call 'parallel
> assignment' (tuple/list assignment) inside 'for-in' loops and list
> comprehensions:

You're probably confused about what's being assigned to what inside the
comprehension. Maybe this will clear it up:

> 1)
> 
>>>>[f + g for f, g in (1, 2), (3, 4)]
> 
> [3, 7]

[(1, 2), (3, 4)] is your 'source' list, so the first time f = 1 and g =
2, then f = 3 and g = 4. I'm guessing you have no problem with the
output given.

> 2)
> 
>>>>x = 'ab'
>>>>y = 'cd'
>>>>[f + g for f, g in x, y]
> 
> ['ab', 'cd']

[x, y] is your 'source' list. For x, f = 'a' and g = 'b'. For y, f = 'c'
and g = 'd'.

> 3)
> 
>>>>f, g = '123', '456'
>>>>[f + g for f, g in '123', '456']
> 
> Traceback (most recent call last):
>   File "<pyshell#55>", line 1, in -toplevel-
>     [f + g for f, g in '123', '456']
> ValueError: too many values to unpack

Here you're in trouble because the strings are the wrong length. Your
second example worked, whether intentionally or by coincidence, because
the strings were both 2 characters long, and you were unpacking them
into two variables. Here you're trying to unpack 3 items ('1', '2', '3',
 then '4', '5', '6') into 2 variables, which doesn't work.

--
Brian Beck
Adventurer of the First Order



More information about the Tutor mailing list