Sometimes we need to generate lists which follow some natural logic, such as iterating over a sequence and applying some conditions in them. We can use Python's “list comprehension” technique to write compact codes to generate lists. We can loop through a sequence, and apply logical expression.
First, let's look at a special function range – it's used to generate a list of numbers over a range as the name suggests! Try the following code section in the Python IDLE:
[python]>>range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>range(5, 10)
[5, 6, 7, 8, 9]
>>range(0, 10, 2)
[0, 2, 4, 6, 8]
[/python]
So range actually generates a list. We can use it in a for loop. Look at the following example, where we generate a list named myList:
[python]myList = []
for i in range(0, 5):
myList.append(i**2)
print(myList)[/python]
The above code snippet will have following output:
[shell][0, 1, 4, 9, 16][/shell]
We could also create myList in one line of code using list comprehension:
[python]myList = [ i**2 for i in range(0, 5) ][/python]
Cool, huh? Let's see another example. Given a list inputList, let's create a outputList which will contain only elements of inputList having a positive index (elements at index 0, 2, 4, ...). First, let's try achieving this using a loop:
[python]inputList = ["bird", "mammal", "reptile", "fish", "insect"]
outputList = []
for i in range(0, len(inputList), 2):
outputList.append(inputList[i])
print(outputList)[/python]
Now let's see the list comprehension version:
[python]outputList = [inputList[i] for i in range(0, len(inputList), 2)]
print(outputList)[/python]
Both techniques will have the same output:
[shell]['bird', 'reptile', 'insect'][/shell]
As a final example, given a list of integers, let's figure out the odd integers, and create a new list containing those:
[python]input = [4, 7, 9, 3, 12, 25, 30]
output = []
for x in input:
if not x%2 == 0:
output.append(x)
print(output)[/python]
Will print:
[shell][7, 9, 3, 25][/shell]
Same job to accomplish using list comprehension method will be to write something like:
[python]output = [x for x in input if not x%2 == 0]
print(output)[/python]
That's it! Now we are in a position to describe the syntax. We start and end by third braces - “[” & “]” - everything should be enclosed by the braces. The opening brace is followed by an expression, which is followed by a for clause and then zero or more for&if clauses.
List comprehension always returns a list, evaluating the expression we put after the opening brace.
Order of evaluating “for” clauses
If there are more than one for clauses, they will be evaluated in the exact order they get evaluated in loops. For example, note the following list comprehension,
[python]output = [x**y for x in range(1, 5) for y in range(1, 3)][/python]
is similar to:
[python]output = []
for x in range(1,5):
for y in range(1, 3):
output.append(x ** y)[/python]
Both of them give [1, 1, 2, 4, 3, 9, 4, 16] as output.
Now we’ve learned what list comprehension is, its syntax and some examples showing its usage. The question is, why use list comprehension? In many cases, you can achieve the same results without using list comprehension by using the map & lambda functions together. Note, however, that, in most cases, list comprehension is considered faster than map & lambda function put together. Besides, list comprehension makes code compact and easy to read - a must for beautiful coding. Maps also help us to code naturally; for example, we can create a list of all positive numbers using list comprehension just the way we think in our math class!