Iterate using tuple as index

Bengt Richter bokr at oz.net
Thu Mar 10 22:38:54 CET 2005


On Thu, 10 Mar 2005 13:12:31 -0800, James Stroud <jstroud at mbi.ucla.edu> wrote:

>Hello,
>
>Its not obvious to me how to do this. I would like to iterate using a tuple as 
>an index. Say I have two equivalently sized arrays, what I do now seems 
>inelegant:
>
>for index, list1_item in enumerate(firstlist):
>  do_something(list1_item, secondlist[index])
>
>I would like something more like this:
>
>for list1_item, list2_item in (some_kind_of_expression):
>  do_something(list1_item, list2_item)
>
>Practically, I'm not so sure B is better than A, but the second would be a 
>little more aesthetic, to me, at least.
>
>Any thoughts on what "some_kind_of_expression" would be?
>
zip?

 >>> firstlist = [1,2,3]
 >>> secondlist = 'a b c'.split()
 >>> firstlist, secondlist
 ([1, 2, 3], ['a', 'b', 'c'])
 >>> for list1_item, list2_item in zip(firstlist, secondlist):
 ...     print list1_item, list2_item
 ...
 1 a
 2 b
 3 c

Or if your lists are very long, you could use an iterator from itertools, e.g.,

 >>> import itertools
 >>> for list1_item, list2_item in itertools.izip(firstlist, secondlist):
 ...     print list1_item, list2_item
 ...
 1 a
 2 b
 3 c


Regards,
Bengt Richter



More information about the Python-list mailing list