Looping around a simple list of tuples

Terry Reedy tjreedy at udel.edu
Sun Apr 27 07:45:45 CEST 2003


"Martin d'Anjou" <point14 at magma.ca> wrote in message
news:3EAB7213.4030209 at magma.ca...
> I have a list of tuples, each tuple is a (scalar , list)
>
> a=[("r1",[1,2,3]),("r2",[8,9,10]),("r5",[12,14,16])]
>
> for el in a:
>     print el
>     for r,l in el:
>        print "R "+`r`
>        print "L "+`l`
>
> ('r1', [1, 2, 3])
> R 'r'
> L '1'
> Traceback (innermost last):
>    File "<stdin>", line 3, in ?
> ValueError: unpack list of wrong size
>
> In my mind, the 'el' implicit variable is a tuple, and the for r,l
loop should
> just work but it does not. How come?

len(el) == 2, so inner loop (tries to) execute twice
first time, r,l = 'rl' (len == 2), so r= 'r', l='l', as printed
second time, r,l = [1,2,3] (len=3) does not work for reason stated.

perhaps you really meant

for r, l in a:
     print "R "+`r`
     print "L "+`l`
# produces
R 'r1'
L [1, 2, 3]
R 'r2'
L [8, 9, 10]
R 'r5'
L [12, 14, 16]

Terry J. Reedy






More information about the Python-list mailing list