jamieb jamieb -4 years ago 118
Python Question

Using list comprehension in Python to do something similar to zip()?

I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it's a pretty powerful feature that's worth learning.

cities = ['Chicago', 'Detroit', 'Atlanta']
airports = ['ORD', 'DTW', 'ATL']

print zip(cities,airports)
[('Chicago', 'ORD'), ('Detroit', 'DTW'), ('Atlanta', 'ATL')]

How do I use list comprehension so I can get the results as a series of lists within a list, rather than a series of tuples within a list?

[['Chicago', 'ORD'], ['Detroit', 'DTW'], ['Atlanta', 'ATL']]

(I realize that dictionaries would probably be more appropriate in this situation, but I'm just trying to understand lists a bit better). Thanks!

Answer Source

Something like this:

[[c, a] for c, a in zip(cities, airports)]

Alternately, the list constructor can convert tuples to lists:

[list(x) for x in zip(cities, airports)]

Or, the map function is slightly less verbose in this case:

map(list, zip(cities, airports))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download