Thursday, February 11, 2021

List Comprehension in Python

List Comprehension

List comprehension is one of the ways of creating list. List would be created as a result of some operation on a range, set or list based on some condition (optional). 

This makes the list creation easier to code and easy to understand. 

Let's have a look at an example to understand this better. 


Create a list with the list of odd numbers less than 10. 

We will first see how to create a list with out list comprehension. 

Create a list with odd numbers

In the above example we are doing in four steps. 
  • Line - 1: Create an empty list by using square brackets. 
  • Line - 2: for loop on a range of numbers till 10. 
  • Line - 3: if condition to check if the number is an odd number. 
  • Line - 4: add the odd number to the list using append() method. 
Same can be done in a single statement with list comprehension. 

List comprehension in Python

We have embedded for loop and if condition inside the square brackets directly to create a list with odd numbers. 

let's break this statement and see in detail. 

odd_numbers = [number for number in range(10) if number % 2 != 0]
  • square brackets [] to create the list. Similarly {} and () can be used as well to create dictionary, set or generator. We will see more about set and dictionary comprehensions towards the end.
  • number highlighted in green indicate the value to be added to the list. This can include some arithmetic operation as well, we will see an example by using some operation.
  • for number in range(10) to loop through the range from 0 to 9. Any iterable can be used in place of range). 
  • if number % 2 != 0 condition to identify the odd number. 

Let's have a look at another example to create a list with squares of odd numbers less than 10. 

List comprehension in Python

We have replaced number with 'number * number' to calculate the square of an odd number and add to the list. This can be any expression based on the requirement. 

We have looked at creating a list by using one iterable. We can use multiple iterables at the same time to create a list (or nested lists). 

Let's have a look at the example by using two lists. 


Create a list with the product of each element in a list with the elements of another list. 

List comprehension with two lists in Python

In the above example, 
  • We are using one list (even_numbers) and one tuple (odd_numbers). 
  • Two for loops to fetch each element in the list.
    • 'for even in even_numbers' would be considered as the first for loop and for every even number in the list second loop would be repeated. 
    • 'for odd in odd_numbers' would loop through odd_numbers for every element from the first loop.
  • For each combination operation 'even * odd' is calculated and added to the list. 
This is same as using nested for loops with out using list comprehension. 

Nested for loops in Python

Both these examples would return the same list [2, 6, 10, 4, 12, 20, 6, 18, 30]. 

Similarly, we can create nested list (or matrices) using the same instead of creating product. 

Nested lists using List comprehension in Python

We can also use the list comprehension to convert nested lists to a single list (matrix flattening). 

Matrix flattening in Python

In the above example, 
  • First for loop is repeated on the matrix.
  • For every list from the matrix, second for loop is repeated and returns the element.
  • element returned is added to the list created. 

List comprehension is very useful to create the lists, at the same time we need to be aware of not over using it (like using it on more number of lists). This would make this difficult to understand and maintain the code. 

One thing to remember is it becomes extremely difficult to debug when they are not working as expected, specially when we are using multiple lists.

So, it is best to decide whether to use list comprehension or not based on the functionality rather than to using it all the time.

Let's have a look at Set comprehension and Dictionary comprehension with simple examples. 

Set comprehension

Set comprehension is same as list comprehension, only difference is we use curly brackets {} instead of square brackets. Using round brackets () would create a generator not tuple, we will see more about generators in different post. 

Set comprehension in Python

Dictionary comprehension

Dictionary comprehensions are also similar to set comprehensions. Only difference is it requires the key to be added. 

Let's have a look at an example. 

Dictionary comprehension in Python

In the above example, we are considering the number in the range as a key and square of the number as corresponding value. 

We can also use dictionary with the list of keys supplied from a list. 

Dictionary comprehension in Python

In the above example, 
  • We are creating a list with the keys required to be in the dictionary. 
  • Using List comprehension to get the squares of odd numbers in the range of 10. 
  • Dictionary comprehension to loop through the list of keys and assign the output of list comprehension as a value to the key. 

Hope the above was a bit of help to understand the List comprehension in Python. 

If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

No comments:

Post a Comment

Different Ways of Sorting Data in a List - Python

Sorting Data in a List List is a collection of data (of different data types), much like an array. Like any data structure or data set, dat...