A Byte of Python

List Comprehension

List comprehensions are used to derive a new list from an existing list. For example, you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 but only when the number itself is greater than 2. List comprehensions are ideal for such situations.

Using List Comprehensions

Example 15.1. Using List Comprehensions

				
#!/usr/bin/python
# Filename: list_comprehension.py

listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo
				
				

Output

				
$ python list_comprehension.py
[6, 8]
				
				

How It Works

Here, we derive a new list by specifying the manipulation to be done (2*i) when some condition is satisfied (if i > 2). Note that the original list remains unmodified. Many a time, we use loops to process each element of a list, the same can be achieved using list comprehensions in a more precise, compact and explicit manner.