List Comprehension in Python
List Comprehension in Python

List Comprehension in Python

Python list is the most versatile and effective Data Type in Python programming. We know that list has several applications in Python programming due to its flexible nature. Lists are mutable, ordered sequences of objects, and their elements are easily accessible and modifiable. In addition to these basic characteristics of a Python List, Python provides a very effective concept known as List Comprehension. List Comprehension is a method of defining a List from any other iterable. It is used to create a new list from other iterable objects like a list, tuple, set, or a string in python. The elements of the new list may be defined such that they should satisfy a particular Condition.

How to define List Comprehension in Python?

List comprehensions are defined inside square brackets.

Syntax :– new_list = [expression for member in iterable if condition]

As we can see from the syntax, list comprehension in Python includes three elements, an expression, iterable, and a condition. Before we discuss these three elements let’s see an example.

We will be creating a new list from an existing list containing some integer values. Here, we want to have square of all even numbers from the old list.

#existing list that we have
old_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#creating new list using list comprehension
new_list = [x ** 2 for x in old_list if x % 2 == 0]
print('New list:', new_list)

Output:

New list: [4, 16, 36, 64, 100]

Now with the help of the above example let’s discuss all three elements.

Expression

In our example, the first part of list comprehension (x ** 2 ) is said to be the Expression.

Expression is nothing but the item we want to insert in our new list. Since here we want to insert square of elements, we have defined our expression as x ** 2.

We get an expression from the member of the iterable itself. We call it an expression because we write it in a form of an expression. It may be as simple as just a single variable or it could include more than one variable and operators as well.

Iterable

As we know an iterable refers to the sequence of Python objects. It can be a list, tuple, string, set, etc., or a function (like range()) that generates a sequence. This will be the collection from which we are creating or defining our new list. For our new list, we will be considering all the members of this iterable.

In our example, the old_list is the iterable we are using for comprehension.

Condition

As the name suggests Condition will be just a condition, we want our elements to satisfy. We write it using Python conditional statements i.e., if-else. In our example, the last part inside the list comprehension [ if x % 2 == 0 ] is the condition. This is the condition to check whether the number is even or not.

When and why should we use List Comprehension in Python?

We should use list comprehension whenever we want to create a list based on another sequence of objects and satisfying a condition. Now the question is why use List Comprehension instead of the traditional approach using iteration?

We know that a Python list uses Iteration to iterate through all its elements. We generally use for loop for iteration. This is the traditional approach to access each element of the list.

Now we will see some examples and will create the lists using both basic iteration and list comprehension. Then we’ll try to figure out how comprehension proves to be more efficient than the normal iteration.

Example 1 – Create the list of all the characters of the string ‘Python programming’

Using the traditional approach, we will first create an empty list and then use for loop to iterate through the string and append each character to the list.

mystr = "Python programming"
#initializing new list
mylist = []
#using traditional approach
for character in mystr:
    mylist.append(character)

print("New list:", mylist)

Output:

New list: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']

Now we’ll do the same task using list comprehension.

mystr = "Python programming"

#using list comprehension
mylist = [character for character in mystr]
print("New list:", mylist)

Output:

New list: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
Example 2 – Create a list from the given list of strings where only such strings are to be included which contains the letter ‘u’.

Using the traditional approach.

old_list = ['tiger', 'vulture', 'cobra', 'wolf', 'unicorn']
new_list = []

#using traditional approach
for word in old_list:
    if 'u' in word:
        new_list.append(word)
print('New list:', new_list) 

Output:

New list: ['vulture', 'unicorn']

Using list comprehension.

old_list = ['tiger', 'vulture', 'cobra', 'wolf', 'unicorn']

#using list comprehension
new_list = [word for word in old_list if 'u' in word]

print('New list:', new_list) 

Output:

New list: ['vulture', 'unicorn']
Example 3 – Create a list of integers less than 15 that are either divisible by 3 or 5.

Using the traditional approach.

#using traditional approach
new_list = []
for num in range(15):
    if num % 3 == 0 or num % 5 == 0:
        new_list.append(num)

print('New list:', new_list)

Output:

New list: [0, 3, 5, 6, 9, 10, 12]

Using list comprehension.

#using list comprehension
new_list = [num for num in range(15) if num % 3 == 0 or num % 5 == 0]

print('New list:', new_list)

Output:

New list: [0, 3, 5, 6, 9, 10, 12]

From the three examples above, we can easily see the difference between the amount of code we used in both approaches. In comparison to the traditional approach, the code in list comprehension was much smaller, simpler, and efficient. In the case of the traditional approach we have first iterated over all the elements, then used conditional statements to check conditions, and then we have appended elements to our list. While in the case of List Comprehension all this work was done in a single line of code.

That’s why we prefer list comprehension over the traditional approach for such problems.

What is Nested List Comprehension in Python?

Nested List Comprehension refers to a list comprehension within another list comprehension. We use it to generate or create nested lists i.e., a list within a list. In other words, we can say whenever we want to define a list of lists, we use nested list comprehensions.

Let’s understand this concept with the help of an example. Suppose we want to create a list of lists of the first four multiples of the first four natural numbers. That means for each natural number we will have one list that will contain its first four multiples and all this will be stored inside the outer list.

Here also we will solve the given problem using both the traditional approach as well as nested list comprehension.

Using traditional approach (nested for loops).

#initializing outer list
nested = []

#using nested for loops
for num in range(1, 5):
    #appending empty sublist
    nested.append([])
    for mult in range(1, 5):
        #appending first four multiples
        nested[num - 1].append(num * mult)

print("Nested list:", nested)

Output:

Nested list: [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]

Using nested list comprehension in Python.

#using nested list comprehension
nested = [[num * mult for mult in range(1, 5)] for num in range(1, 5)]
print("Nested list:", nested)

Output:

Nested list: [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]

So, we can clearly see the difference between the traditional approach and nested list comprehensions. Using nested list comprehensions, we were able to create nested lists much efficiently.

Conclusion

In this article, we have read about list comprehensions, nested list comprehensions, and their comparison with for loops. We can conclude the benefits of list comprehension in Python with the following points.

  • It is a more efficient way to define and construct lists based on existing Sequences.
  • It requires much lesser code than the for loops.
  • It is generally simpler and faster than constructing lists from loops and functions.

Piyush Sharma

Third-year computer engineering student inclined towards the latest trends and technology. Always keen to explore and ready to learn new things. To read more articles on Python, stay tuned to avidpython.com.

Leave a Reply