List Comprehension in Python

List Comprehension in Python: List is one of the most important Data Structures available in Python.

As you already know that list is a collection of data elements separated by, (comma) inside the [ ] (square brackets).

So, there are different ways of initializing a list in Python.

One of them is to simply assign the data elements in the list.

example = [1, 2, 3, 4, 5]

The other method and the popular one is to use For Loop in order to iteratively assign the elements in our list.

For this, we make use of the append() function.

example = []
for i in range(1, 5):
    example.append(i)

However, there is also another approach which we are going to discuss in this article which is List Comprehension.

So, before jumping into it, let’s take a look at some of the benefits of List Comprehension in Python.

Benefits of using List Comprehension

Here are the top 5 benefits of using List Comprehension in Python:

  1. Less Code Required – With List Comprehension, your code gets compressed from 3-4 lines to just 1 line.

  2. Better Performance – List Comprehension boosts the performance of your program as compared to the normal For Loop approach.

  3. Easy to Understand – List Comprehension is much easier to understand and implement as compared to the normal approach.

  4. Refactoring Code Smell – With List Comprehension, your code becomes much readable and easy to understand for other programmers.

Basic Syntax

List Comprehension is a fast and simple way for assigning elements to the list and have various advantages over the normal For Loop approach.

So, let us take a look at the basic syntax to implement the List Comprehension in Python.

list_name = [var for var in elements]

Here list_name is the empty list in which we have to assign the elements, var is the temporary variable which will return the value in the list and elements are the set of elements or iterative objects.

So, every time a For Loop iterate over elements (which is a set of element), var value get changes to that particular element and gets assigned to the list_name.

Now, we will take a deep look at List Comprehension and their working.

For Loop vs List Comprehension

For Loop is the most popular approach for assignment elements in the list.

By using For Loop, we can copy the elements of the existing list in our new and empty list.

So, we will create our new list using the existing list or iterable.

Let’s understand this with the help of an examples of Python Code.

city1 = ["Paris", "London", "Berlin", "Tokyo", "Sydney"]
city2 = []

for x in city1:
    city2.append(x)

print(city2)

Output:
[‘Paris’, ‘London’, ‘Berlin’, ‘Tokyo’, ‘Sydney’]

As you can see that city1 is the existing list of String and city2 is the new and empty list.

So, we have iteratively selected each element from the city1 list and assigned it to the empty list which is city2, with the help of the append() function.

Now, lets create the same code with the help of List Comprehension.

city1 = ["Paris", "London", "Berlin", "Tokyo", "Sydney"]
city2 = []

city2 = [x for x in city1]

print(city2)

Output:
[‘Paris’, ‘London’, ‘Berlin’, ‘Tokyo’, ‘Sydney’]

Now as you can see that our entire code is compressed into a single line of code, which is the beauty of list comprehension.

In list comprehension, we write our code inside the square brackets ([ ]), which signifies that we are creating a list.

The first expression inside this square bracket (which is x in this case) is going to be executed iteratively (every time a For Loop is executed) and will return the value as a new element in the list.

As in the above code, you can see that the first expression inside the square bracket is x.

list2 = [x for_loop]

So, it is similar to

for_loop:

list2.append(x)

Every time the For Loop runs, x is the expression that is also going to execute and return the value to the list2.

Let’s take another example in which we are going to iterate over String instead of a list.

str1 = "singapore"
str2 = []

for x in str1:
    str2.append(x)

print(str2)

Output:
[‘s’, ‘i’, ‘n’, ‘g’, ‘a’, ‘p’, ‘o’, ‘r’, ‘e’]

Here we are iterating over the str1 string with the help of For Loop.

So, every time a For Loop runs, a single character is appended into the new list which is str2.

Now converting this For Loop code into List Comprehension Code will look like this.

str1 = "singapore"
str2 = []

str2 = [x for x in str1]

print(str2)

Output:
[‘s’, ‘i’, ‘n’, ‘g’, ‘a’, ‘p’, ‘o’, ‘r’, ‘e’]

Similarly in this code, the first expression is returned into the list every time the For Loop is iterted over str1 string.

Let’s take a look at another program, which uses range() with the For Loop.

numbers = []

for i in range(1, 10):
    numbers.append(i)

print(numbers)

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In this program, i is iterated over the range of numbers from 1 to 10 and i is appended into the empty list which is numbers.

Here is the List Comprehension code equivalent to the above code.

numbers = []

numbers = [ i for i in range(1, 10)]

print(numbers)

Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Conditional List Comprehension

Now that you have seen the basic concept of list comprehension and how does it work.

Let us take a look at Conditional List Comprehension, in which we use conditional statements, like – if or else inside the For Loop.

Here is a normal approach for assigning the elements inside the empty list by using For Loop and conditional statements.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_no = []

for i in numbers:
    if i%2 == 0:
        even_no.append(i)

print(even_no)

Output:
[2, 4, 6, 8, 10]

List Comprehension of the above code is

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_no = []

even_no = [i for i in numbers if i%2 == 0]

print(even_no)

Output:
[2, 4, 6, 8, 10]

As you can see that in this code we have added the conditional statement after the For Loop statement.

If the condition is true, the first expression inside the square brackets will get executed (which in this case is x) and get returned to the empty list (which is even_no).

Now lets take another example in which we have used if condition inside the 2 nested For Loops.

list1 = ['q', 'a', 't', 'd', 'o', 'f', 'e']
list2 = ['a', 'e', 'i', 'o', 'u']

result = []

for i in list1:
    for j in list2:
        if i == j:
          result.append(i)

print(result)

Output:
[‘a’, ‘o’, ‘e’]

Converting this code into Conditional List Comprehension code will give us

list1 = ['q', 'a', 't', 'd', 'o', 'f', 'e']
list2 = ['a', 'e', 'i', 'o', 'u']

result = [i for i in list1 for j in list2 if i == j]

print(result)

Output:
[‘a’, ‘o’, ‘e’]

Here we have used 2 For Loops followed by a conditional statement inside the square brackets.

If the condition gets true, the first expression (which is x) will get executed and automatically get appended in the list (which is the result).

Using List Comprehension with Functions

We can also use functions with List Comprehension. However, before first let’s see the working of function with normal For Loop approach.

def power(x):
    return x**2

p_num = []

for x in range(1, 10):
    p_num.append(power(x))

print(p_num)

Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Here we have defined the power() function and used it as a argument for the append() function.

Below is the equivalent code of the above For Loop approach and here we have used the List Comprehension.

def power(x):
  return x**2

p_num = [power(x) for x in range(1, 10)]

print(p_num)

Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Lambda Functions vs List Comprehensions

Lambda function is a small anonymous function that takes multiple arguments, has a single expression inside the function body, and returns a value.

Here is the basic syntax of the lambda function.

function_name = lambda arguments: expression

Here function_name is the actual name of the function which we want to create.

lambda is the keyword which is used for defining the lambda function, arguments are the arguments of function and expression is the statement which we want to return from the function.

Below is the code for using lambda function for assigning the list elements.

numbers = [1, 5, 7, 10, 3, 25, 12, 20]

result = list(filter(lambda x: x%5 == 0, numbers))

print(result)

Output:
[5, 10, 25, 20]

Here we have also used a filter() function, which takes 2 arguments. The first one is the lambda function and the second is the list of a parameter for the lambda function.

With the help of filter(), our lambda function iteratively takes all the parameters from numbers and returns the value of a list element to the result list.

Hope you understood the concept of List Comprehension in Python and their working. We also have an article on the advantages and uses of Python, which you must take a look at.

Subscribe to our Newsletter

Get regular updates and tips related to Programming and Software Development, right in your Inbox.

* indicates required