List Comprehension in Python

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:

[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]

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:

myList = []
for i in range(0, 5):

The above code snippet will have following output:

[0, 1, 4, 9, 16]

We could also create myList in one line of code using list comprehension:

myList = [ i**2 for i in range(0, 5) ]

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:

inputList = ["bird", "mammal", "reptile", "fish", "insect"]
outputList = []
for i in range(0, len(inputList), 2):

Now let’s see the list comprehension version:

outputList = [inputList[i] for i in range(0, len(inputList), 2)]

Both techniques will have the same output:

['bird', 'reptile', 'insect']

As a final example, given a list of integers, let’s figure out the odd integers, and create a new list containing those:

input = [4, 7, 9, 3, 12, 25, 30]
output = []
for x in input:
   if not x%2 == 0:

Will print:

[7, 9, 3, 25]

Same job to accomplish using list comprehension method will be to write something like:

output = [x for x in input if not x%2 == 0]

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,

output = [x**y for x in range(1, 5) for y in range(1, 3)]

is similar to:

output = []
for x in range(1,5):
   for y in range(1, 3):
      output.append(x ** y)

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!

Leave a Reply

Your email address will not be published. Required fields are marked *