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:

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
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
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
0 a1 b1
1 a2 b2
2 a3 b3

No comments:


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

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.