Python List Comprehension

Python list comprehension is a feature of the language that allows us to create lists in a concise and expressive way. It is a concise and elegant way to create lists using an iterable. And also the most efficient and elegant alternative over for loops and the built-in list() function.

A Python list is a collection that is ordered and mutable, allowing duplicate elements. Each element in a list is enclosed in square brackets [] and separated by commas. With list comprehension, we can create a list in a single line of code. It makes it a powerful and efficient tool for manipulating data in Python.

List comprehension is useful when working with large amounts of data. It is also helpful when we need to perform operations on multiple elements in a list. In this article, we will explore the use of list comprehension in Python, with examples and explanations.

Quick Examples of Python List Comprehension

Following are a few examples of the many ways to use list comprehension.

# List using simple list comprehension 
alphabets = [chr(x) for x in range(ord('a'), ord('z')+1)]

# Define a list 
my_list = ['python', 'java', 'php', 'go']
# Use list comprehension to iterate 
first_letters = [language[0] for language in my_list]

# Use list comprehension and if, else conditions
modified_list = [language + " language" if len(language) > 4 else language for language in my_list]

# Using nested list comprehension to create a nested list
nested_list = [[i*j for j in range(1,4)] for i in range(1,4)]

1. List Comprehension

With python list comprehension, we can create lists by specifying the elements. We select elements that we want to include, along with any conditions or operations. All this is done in a single line of code.

1.1 Syntax of List Comprehension

The general syntax for list comprehension is as follows:

# Syntax
new_list = [expression for item in iterable if condition]
  • expression is the operation you want to perform on each element.
  • item is a variable that will be assigned to each element in the iterable.
  • iterable is a sequence of items.
  • condition (optional) is a boolean expression that is evaluated for each item

# Create list using comprehension
even_numbers = [x for x in range(1,11) if x % 2 == 0]

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

1.2 Syntax of Nested List Comprehension

The syntax for a nested list comprehension is similar to a regular list comprehension. However with an additional set of square brackets surrounding the inner comprehension.

# Syntax
nested_list = [[expression for item in inner_iterable if inner_condition] for outer_item in outer_iterable if outer_condition]

Nested list comprehension is a bit different from normal list comprehension.

# Create nested list using comprehension
nested_list = [[i*j for j in range(1,4)] for i in range(1,4)]

# Output:
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

2. List Comprehension as Replacement of FOR Loops

The readability of list comprehension makes it a great alternative to traditional for loops. The for loops which can often be more verbose and harder to read can be replaced by List Comprehension.

Below is why a List Comprehension can be a replacement over for Loops:

  1. Improved readability.
  2. Increased performance
  3. Concise and expressive
  4. Suitable for functional programming
  5. More pythonic way of coding

Below are some examples of using a for loops.

# Example No 1: 
# Using a for loop
filtered_list = []
for x in my_list:
    if x.startswith('p'):
# Output: ['python', 'php']

# Example No 2
lengths = []
for x in my_list:
# Output: [6, 4, 3, 2]

Let’s write the above two examples using python list comprehension.

# Example No 1: 
# Using list comprehension
filtered_list = [x for x in my_list if x.startswith('p')]
# Output: ['python', 'php']

# Example No 2
# Using list comprehension
lengths = [len(x) for x in my_list]
# Output: [6, 4, 3, 2]

3. Multiple FOR Loops in List Comprehension

Using this technique, you can perform operations on multiple lists at the same time. It involves using multiple for loops in a single list comprehension, allowing you to iterate over multiple lists and create a new list based on the values of the input lists.

Here is an example of using two lists and combining them using two for loops:

# Create lists
list_1 = ['Python', 'Java', 'C++', 'JavaScript']
list_2 = ['Django', 'Spring', 'STL', 'React']

# Using multiple for loops in list comprehension
combined_list = [(language, framework) for language in list_1 for framework in list_2 if 

# Output: 
# [('Python', 'Django'), ('Java', 'Spring'), ('C++', 'STL'), ('JavaScript', 'React')]

4. Conditional Statement with List Comprehension

Conditional Statements inside list comprehension can be used as mentioned above. It allows you to create a new list or modify the existing list based on certain conditions.

4.1 If Condition

Using if condition inside the list comprehension is very common and easy. This type of list comprehension uses an if statement to filter the elements of the list.

# Using if condition in list comprehension
filtered_list = [language for language in my_list if language.startswith('J')]

# Output: 
# ['Java', 'JavaScript']

4.2 Multiple if Conditions

In the following examples, we have used multiple if conditions. We first check if a list item starts with the letter J .Then further we check if it ends with t or not.

# Using multiple if condition in list comprehension
filtered_list = [language for language in list_1 if language.startswith('J')  if language.endswith('t')]

# Output:
# ['JavaScript']

4.3 if-else Condition

Using the if-else condition inside list comprehension is a powerful way to filter and modify the list based on certain conditions.

# Using if-else condition in list comprehension
transformed_list = [language.upper() if language.startswith('J') else language for language in list_1]

# Output: 
#['Python', 'JAVA', 'C++', 'JAVASCRIPT']

Side Note: it can make the code less readable and harder to understand if the conditions are too complex

5. Scenarios Comprehension Not Usefull

While list comprehension is a powerful and versatile tool for working with lists, there are some cases where a for loop may be more appropriate. Here are a few examples:

  1. When the logic of the operation is too complex for a single line of code
  2. When the operation involves side-effects
  3. When you need to iterate over multiple lists
  4. When you need to iterate over an infinite list
  5. When you need to use the index of the element
  6. When you need to use try and except block

# Using a for loop
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
    if number % 2 == 0:
        squared_numbers.append(number ** 2)
        squared_numbers.append(number ** 3)

# Output:
# [1, 4, 27, 16, 125]

The above example can be very complex while using list comprehension so better use the traditional method. Though it is possible but less readable.

numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 if number % 2 == 0 else number ** 3 for number in numbers]

# Output: 
#[1, 4, 27, 16, 125]

6. Conclusion

In this article, we have explained What is List Comprehension with Examples. This article will help you, to use list comprehension more effectively.

We have explained the syntax of List Comprehension. We have also discussed the nested List comprehension with examples. If you have any questions, please let me know in the comment section.

Happy Learning!!!

Related Articles


I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply

You are currently viewing Python List Comprehension