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



This is my OLD blog. I've copied this post over to my NEW blog at:

http://www.saltycrane.com/blog/2008/04/how-to-use-pythons-enumerate-and-zip-to/

You should be redirected in 2 seconds.



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

No comments:

About

This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

http://www.saltycrane.com/blog/.

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.