Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 830
jamieb Avatar asked Jan 30 '10 22:01

jamieb


People also ask

What is zip in list comprehension?

Dictionary comprehensions Use the zip() function to create a new dictionary from each list of keys and values.

What is Python list comprehension used for?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list.

Why might you use a list comprehension instead of a loop in Python?

List comprehension is used for creating lists based on iterables. It can also be described as representing for and if loops with a simpler and more appealing syntax. List comprehensions are relatively faster than for loops. The syntax of a list comprehension is actually easy to understand.

Can you do list comprehension in Python?

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.


1 Answers

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))
like image 178
Greg Hewgill Avatar answered Sep 25 '22 02:09

Greg Hewgill