Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

How to use Python's enumerate and zip to iterate over two lists and their indices.

enumerate - Iterate over indices and items of a list
The Python Cookbook (Recipe 4.4) describes how to iterate over items and indices in a list using enumerate. For example:
alist = ['a1', 'a2', 'a3']

for i, a in enumerate(alist):
    print i, a
yields:
0 a1
1 a2
2 a3

zip - Iterate over two lists in parallel
I previously wrote about using zip to iterate over two lists in parallel. Example:
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for a, b in zip(alist, blist):
    print a, b
yields:
a1 b1
a2 b2
a3 b3

enumerate with zip
Here is how to iterate over two lists and their indices using enumerate together with zip:
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for i, (a, b) in enumerate(zip(alist, blist)):
    print i, a, b
yields:
0 a1 b1
1 a2 b2
2 a3 b3

3 Comments — feed icon Comments feed for this post


#1 Jeremy Lewis commented on 2009-05-29:

If you're working with last lists and/or memory is a concern, using the itertools module is an even better option.

from itertools import izip, count
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']

for i, a, b in izip(count(), alist, blist):
    print i, a, b

yields the exact same result as above, but is faster and uses less memory.


#2 Jeremy Lewis commented on 2009-05-29:
>>> def foo():
...  for i, x, y in izip(count(), a, b):
...   pass
...
>>> def bar():
...  for i, (x, y) in enumerate(zip(a, b)):
...   pass
...
>>> delta(foo)
0.0213768482208
>>> delta(bar)
0.180979013443

where a = b = xrange(100000) and delta(f(x)) denotes the runtime in seconds of f(x).


#3 Eliot commented on 2009-05-29:

Jeremy,
Thanks for the tip and the clear example and demonstration of the performance benefit. I had heard of itertools but have not really used it. It was great to talk to you today and I hope I can talk to you again soon.

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Slicehost