Iterating through two lists in parallel using zip()
From
the Python docs, zip returns
a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables. This is useful
for iterating over two lists in parallel. For example, if I have two
lists, I can get the first element of both lists, then the
second element of both lists, then the third, etc.
Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> a = [1,2,3] >>> b = ['a','b','c'] >>> for i,j in zip(a,b): ... print i, j ... 1 a 2 b 3 c >>>
If the lists are different lengths, zip truncates to
the length of the shortest list. Using map
with None is similar to zip except the
results are padded with None.
>>> a = [1,2,3] >>> b = ['a','b','c','d'] >>> zip(a,b) [(1, 'a'), (2, 'b'), (3, 'c')] >>> map(None,a,b) [(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd')] >>>
If I have a list of keys and a list of values, I can create a
dictionary by passing the output of zip
to dict.
>>> mykeys = ['a', 'b', 'c']
>>> myvalues = [1, 2, 3]
>>> dict(zip(mykeys, myvalues))
{'a': 1, 'c': 3, 'b': 2}
>>>
See also this thread on the Python mailing list: Iterating through two lists
Post a comment
About
I'm Eliot and this is my notepad for programming topics such as Python, Django, Ubuntu, Emacs, etc... more »
Search Blog
Tags
-
algorithms
(4)
-
aws
(8)
-
blogproject
(20)
-
c_cplusplus
(12)
-
cardstore
(8)
-
colinux
(2)
-
concurrency
(9)
-
conkeror
(2)
-
cygwin
(18)
-
datastructures
(15)
-
datetime
(3)
-
dell
(3)
-
django
(39)
-
emacs
(20)
-
files_directories
(10)
-
install_setup
(7)
-
javascript
(3)
-
keyboard
(6)
-
matplotlib
(5)
-
mercurial
(4)
-
nginx
(2)
-
preferences
(8)
-
processes
(3)
-
pyqt
(18)
-
python
(122)
-
ratpoison
(3)
-
regexes
(5)
-
rsync
(3)
-
softwaretools
(17)
-
sql
(13)
-
ssh
(7)
-
subversion
(6)
-
twisted
(6)
-
ubuntu
(60)
-
urxvt
(5)
-
vxworks
(25)
-
webservices
(4)
-
wmii
(7)
Blogroll
- Adam Gomaa
- Alex Clemesha
- Amir Salihefendic
- Armin Ronacher
- David Beazley
- David Ziegler
- Duncan McGreggor
- Gareth Rushgrave
- Glyph Lefkowitz
- Guido van Rossum
- Ian Bicking
- Jacob Kaplan-Moss
- James Bennett
- James Tauber
- Jesper Noehr
- Matt Harrison
- Nikolay Kolev
- Parand Darugar
- Peter Baumgartner
- Peter Bengtsson
- Rob Hudson
- Simon Willison
- Will McGugan