Iterating throught 2 lists at the same time

Jeff Shannon jeff at ccvcorp.com
Thu Aug 23 20:13:43 EDT 2001


Lee Harr wrote:

> On Thu, 23 Aug 2001 17:16:17 -0400, Rajarshi Guha <rajarshi at seed.chem.psu.edu>:
> > Hi,
> >   I have the following construct:
> >
> >>>> a = ['a','b','c']
> >>>> b = ['x','y','z']
> >>>> for i,j in a,b:
> > ...     print i,j
> > ...
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > ValueError: unpack list of wrong size
> >
> >
>
> how about:
>
> for c in zip(a,b):
>    print c

Another possibility:

for i in range(len(a)):
    print a[i], b[i]

though this requires that care be taken if the lists are of different lengths... so
probably the zip() method is better.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list