Faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 5 of 5 people (100%) answered Yes

Entry

How do I loop through 2 (or more) lists at the same time?

Jun 4th, 2002 07:44
Michael Chermside,


Python's for loop makes it very easy to go through the items in a list:
Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> li = [1,2,3]
>>> for x in li:
...     print x
...
1
2
3
But what if you want to go through two or more lists at once?
>>> list_1 = [1,2,3,4]
>>> list_2 = ['a','b','c','d']
One very basic but perfectly workable approach is to use an counter:
>>> for i in range(len(list_1)):
...     print '%i - %s' % (list_1[i], list_2[i])
...
1 - a
2 - b
3 - c
4 - d
But this is somehow unsatisfying. It requires the creation of the an
index which serves no particular purpose other than allowing the loop,
and it does not handle lists of different lengths gracefully.
You may prefer the following approach:
>>> for x,c in zip(list_1, list_2):
...     print '%i - %s' % (x, c)
...
1 - a
2 - b
3 - c
4 - d
The zip() function is so-named because it interleaves the items of the
lists in a zipper-like fashion, creating a list of tuples, one from each
list. It can work on any number of items, and if the lists are of
different lengths, it will stop as soon as it exhausts the shortest list:
>>> import sys
>>> for x,y,c in zip(list_1, xrange(sys.maxint), list_2):
...     print '%i (%i) %s' % (x,y,c)
...
1 (0) a
2 (1) b
3 (2) c
4 (3) d
If you need to iterate as many times as the *longest* list, you can use
a slightly different idiom which pads the shorter lists with None. (But
generally zip() is better.)
>>> for x,y,z in map(None, list_1, list_2, range(6)):
...     print '%s (%s) %s' % (x,y,z)
...
1 (a) 0
2 (b) 1
3 (c) 2
4 (d) 3
None (None) 4
None (None) 5
For some more interesting speculations on this topic, see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52233