How to Use List Comprehension in Python

How to Use List Comprehension in Python

23 May 2024
Intermediate
260 Views
13 min read

Python List Comprehension

Have you ever come across a bunch of data where you need to filter out some elements or perform certain operations on each item? You might even want to create a whole new list based on the original one. If yes, then you might have wondered if there is a single term that will make it possible to do all of this. Well, we will be learning about just that- Python List Comprehension!

In this Python Tutorial, we will try to understand Python List Comprehension and various uses of List Comprehension in Python. If you are new to Python Programming, you should first go through all the basic concepts. Python Certification Training would be the best place to get you started with Python Development.

Read More: Top 50 Python Interview Questions and Answers

What is Python List Comprehension?

List Comprehension in Python is a way through which we can write concise, readable codes while we are creating lists in our Python program. Traditionally, you might be using loops and conditionals and even writing several lines of code to achieve the same result. It's time for you to stop and get the easy way with list comprehension that will let you do it all in just one line. Sounds simple right?

Let's look at the basic structure of using list comprehension in a Python program.

Syntax of List Comprehension in Python

new_list = [expression for item in original_list if condition]
Here,
  • expression- this will hold what has to be done with each item in the original list.
  • item- this is the variable that holds each element in the original list.
  • original_list-this is the list you are iterating over.
  • condition- it is an optional condition that will help filter elements.

Example of List Comprehension in Python

Below is an example to better explain to you the working of list comprehension in Python Compiler.
# Original list
numbers = [1, 2, 3, 4, 5]

# List comprehension to double each number
doubled_numbers = [num * 2 for num in numbers]

print(doubled_numbers)
Here, the expression 'num * 2' will double each number. We have the original list as 'numbers' and variable 'num' which represents each element in the 'numbers' list.

Output

[2, 4, 6, 8, 10]

for Loop vs. List Comprehension

Traditionally, we use Python for loops when working with lists in Python. It is no doubt more versatile and needed in many cases but list comprehension offers a more compact and concise way of achieving the same results as compared with for loop. Below is a comparison table based on different aspects:
Aspectfor LoopList Comprehension
PerformanceThe 'for' loop is slightly low in terms of performance.List comprehension has optimized implementation which results in better performance in many cases.
Code LengthIt requires more lines.It is more concise as compared to for loop.
Readabilitythe code has comparatively less readability.It has more concise and readable code.
ScopeIt defines the empty list beforehand and then modifies it within the loop.It creates a new list in a single expression which is scoped to the comprehension itself.

Suppose, we have a list of numbers and we want to create a new list that will display only the even numbers. We will try to use both for loop and list comprehension to understand the difference.

Example using Traditional 'for' Loop:

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Empty list to store even numbers
even_numbers = []

# Loop to filter even numbers
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(even_numbers)

Output

[2, 4, 6, 8, 10]

Example using List Comprehension:

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)

Output

[2, 4, 6, 8, 10]
As you can see, we got the same output in both cases but using list comprehension, we did it in a slightly shorter time, that too, in a single line of code.
Read More: Python Developer Salary

Using Conditions in List Comprehension

We can also use conditional statements in list comprehensions. In this way, we can filter out elements from the original list by giving them specific conditions.
Let's try adding an if statement in an example program in Python Editor.
# Original list
words = ["apple", "banana", "orange", "kiwi", "pear", "strawberry"]

# List comprehension to filter words with more than 5 characters
long_words = [word for word in words if len(word) > 5]

print(long_words)
len(word) > 5 is the conditional statement here that will check if the length of the word is greater than 5 or not. If true, only then, will it be displayed.

Output

['banana', 'orange', 'strawberry']
Now try adding an else statement that will specify a default value for elements that don't meet the condition.
# Original list
numbers = [1, 2, 3, 4, 5]

# List comprehension to label even and odd numbers
even_or_odd = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(even_or_odd)
If the element meets the if condition num % 2 == 0, 'Even' will be displayed. Else, 'Odd' will be displayed.

Output

['Odd', 'Even', 'Odd', 'Even', 'Odd']

Nested List Comprehensions

Nested list comprehensions allow us to create lists of lists. They are very useful in creating matrices, lists of lists, or any hierarchical data structures in python where multiple levels are to be included. Let's try it in an example program in Python Online Compiler.
# Nested list of numbers
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

# Nested list comprehension to transpose the matrix
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

print(transposed_matrix)
Here, we have an outer list comprehension that will iterate over each column index 'i' in the range of the number of columns in the matrix 'range(len(matrix[0]))'. The inner list comprehension '[row[i] for row in matrix]' will iterate over each row in the matrix.

Output

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

Advantages of List Comprehension

List comprehension in Python offers several advantages such as:
  • It allows us to write concisely within a single line of code.
  • It makes the code easier to read and understand.
  • It is rather less complex than the traditional for loops as they don't have temporary variables and separate loop constructs.
  • In many cases, list comprehensions can be seen as having higher performance as compared to traditional loops.
  • They support a wide range of operations like filtering, mapping, and nesting.
Conclusion
List Comprehension in Python is quite useful and easier in many ways. If we know how to use Python List comprehension, we can create more concise and readable Python programs. If you are looking for a step-by-step guide to learning and understanding various Python concepts better and using them in real-time applications, enroll in our Python Certification Course right now!

FAQs

Q1. What is a list comprehension in Python?

A list comprehension in Python is used for writing concise codes to create new lists by applying an operation to each item in an existing one.

Q2. What are the 4 types of comprehension in Python?

The four types of comprehension in Python are:
  1. List Comprehension
  2. Dictionary Comprehension
  3. Set Comprehension
  4. Generator Comprehension

Q3. Is Python list comprehension faster?

Yes, Python list comprehension is faster than traditionally used for loops for creating lists as they are more optimized for performance.

Q4. What are the 2 main types of comprehension?

The two main types of comprehension are:
  1. List Comprehension
  2. Dictionary Comprehension
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Project Jul 16 TUE, THU
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Master Class Jul 20 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this