python list comprehension

In order to be more “pythonic” while writing python code, many best practices are recommended. Python list comprehensions, like “dictionary comprehension” or “set comprehension” or using “warlus operator(introduced in python 3.8 )” is found in use in many python libraries.

Let’s see the basic construct for a python list comprehension.

How to write

new_list = [ expression(i) for i in old_list if condition(i) ]

 

The above expression shows the way a python list comprehension is written. Note that the the right hand side of the “=” starts with “[” and ends with “]” . This means that whatever we write inside the brackets, generates a list, which is the output for ny python list comprehension .

 

Let’s see an example for the same. Here we shall be creating a list of items ( squared by it’s original value -> i*i ) if the value of the item ( i ) is even (i %2 == 0 )

 

new_list = [ i*i for i in old_list if i%2 ==0 ]

Let’s take a look at the below function

def list_comp():
  old_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  new_list = [i * i for i in old_list if i % 2 == 0]
  return new_list

Now if we execute the below function,

     print(list_comp()) 
We will have the below output
    [0, 4, 16, 36, 64] 

The above function uses an old list to generate a new list after applying a filter which checks if the current item is even .

In the above code our expression is i*i and condition is i%2 == 0. For more details let’s look at the github repository for the code.

 

When to use list comprehension ?

When we want to achieve the below points we should consider using a list comprehension in python

      1. create a new list from a computation 
      2. create a list using a declarative approach
      3.  we want to apply some filters while creating the list

Benefits of using list comprehension

      1. As it is a declarative way of creating a new list while using list comprehension, the code becomes more readable.
      2. By using list comprehension we can avoid using loops and map() , and therefore not care about initializing a new list before the start of the loop or not care about the order of augments passed inside the map() . And thus we are better off in writing code
      3. List comprehension also enables us to write code by applying filter-logic to wipe out data that are not important

 

Leave a Reply

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

Doubts? WhatsApp me !