Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Looping Through Multiple Lists

Credit: Andy McKay

Problem

You need to loop through every item of multiple lists.

Solution

There are basically three approaches. Say you have:

a = ['a1', 'a2', 'a3']
b = ['b1', 'b2']

Using the built-in function map, with a first argument of None, you can iterate on both lists in parallel:

print "Map:"
for x, y in map(None, a, b):
    print x, y

The loop runs three times. On the last iteration, y will be None.

Using the built-in function zip also lets you iterate in parallel:

print "Zip:"
for x, y in zip(a, b):
    print x, y

The loop runs two times; the third iteration simply is not done.

A list comprehension affords a very different iteration:

print "List comprehension:"
for x, y in [(x,y) for x in a for y in b]:
    print x, y

The loop runs six times, over each item of b for each item of a.

Discussion

Using map with None as the first argument is a subtle variation of the standard map call, which typically takes a function as the first argument. As the documentation indicates, if the first argument is None, the identity function is used as the function through which the arguments are mapped. If there are multiple list arguments, map returns a list consisting of tuples that contain the corresponding items from all lists (in other words, it’s a kind of transpose operation). The list arguments may be any kind of sequence, and the result is always a list.

Note that the first technique returns None for sequences in which there are no more elements. Therefore, the output of the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata