Nice way of getting items from two lists

Peter Otten __peter__ at web.de
Wed Mar 10 13:04:10 EST 2004


C GIllespie wrote:

> I have two equal size lists - list1, list2. Basically, each item in list 1
> has a partner in list2. I was wanting to do something like
> So if:
> list1=['x','y','z']
> list2=[1,2,3]
> 
> then if I did this 'for loop'
> for name, value in list1,list2:
>     print name, value
> 
> I would get
> x,1
> y,2
> z,3

>>> a = ["a", "b", "c"]
>>> b = [1, 2, 3]
>>> for x, y in zip(a, b):
...     print x, y
...
a 1
b 2
c 3
>>>

zip(list1, list2, ..., listN) creates a new list of N-tuples, so if you are
concerned about memory footprint, use itertools.izip() instead, which does
the zipping (nice metaphor, by the way) on the fly. 

Peter



More information about the Python-list mailing list