Python List Comprehension (With Examples) (2024)

List comprehension offers a concise way to create a new list based on the values of an existing list.

Suppose we have a list of numbers and we desire to create a new list containing the double value of each element in the list.

numbers = [1, 2, 3, 4]

# list comprehension to create new listdoubled_numbers = [num * 2 for num in numbers]

print(doubled_numbers)

Output

[2, 4, 6, 8]

Here is how the list comprehension works:

Python List Comprehension (With Examples) (1)

Syntax of List Comprehension

[expression for item in list if condition == True]

Here,

for every item in list, execute the expression if the condition is True.

Note: The if statement in list comprehension is optional.

for Loop vs. List Comprehension

List comprehension makes the code cleaner and more concise than for loop.

Let's write a program to print the square of each list element using both for loop and list comprehension.

for Loop

numbers = [1, 2, 3, 4, 5]square_numbers = []

# for loop to square each elementsfor num in numbers: square_numbers.append(num * num)

print(square_numbers)# Output: [1, 4, 9, 16, 25]

List Comprehension

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

# create a new list using list comprehensionsquare_numbers = [num * num for num in numbers]

print(square_numbers)# Output: [1, 4, 9, 16, 25]

It's much easier to understand list comprehension once you know Python for loop().

Conditionals in List Comprehension

List comprehensions can utilize conditional statements like if…else to filter existing lists.

Let's see an example of an if statement with list comprehension.

# filtering even numbers from a listeven_numbers = [num for num in range(1, 10) if num % 2 == 0 ]

print(even_numbers)# Output: [2, 4, 6, 8]

Here, list comprehension checks if the number from range(1, 10) is even or odd. If even, it appends the number in the list.

Note: The range() function generates a sequence of numbers. To learn more, visit Python range().

if...else With List Comprehension

Let's use if...else with list comprehension to find even and odd numbers.

numbers = [1, 2, 3, 4, 5, 6]

# find even and odd numberseven_odd_list = ["Even" if i % 2 == 0 else "Odd" for i in numbers]

print(even_odd_list)

Output

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

Here, if an item in the numbers list is divisible by 2, it appends Even to the list even_odd_list. Else, it appends Odd.

Nested if With List Comprehension

Let's use nested if with list comprehension to find even numbers that are divisible by 5.

# find even numbers that are divisible by 5num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]

print(num_list)

Output

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Here, list comprehension checks two conditions:

  1. if y is divisible by 2 or not.
  2. if yes, is y divisible by 5 or not.

If y satisfies both conditions, the number appends to num_list.

Example: List Comprehension with String

We can also use list comprehension with iterables other than lists.

word = "Python"vowels = "aeiou"

# find vowel in the string "Python"result = [char for char in word if char in vowels]

print(result)# Output: ['o']

Here, we used list comprehension to find vowels in the string 'Python'.

More on Python List Comprehension

Nested List Comprehension

We can also use nested loops in list comprehension. Let's write code to compute a multiplication table.

multiplication = [[i * j for j in range(1, 6)] for i in range(2, 5)]print(multiplication)

Output

[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]

Here is how the nested list comprehension works:

Python List Comprehension (With Examples) (2)

Let's see the equivalent code using nested for loop.

Equivalent Nested for Loop

multiplication = []for i in range(2, 5): row = [] for j in range(1, 6): row.append(i * j) multiplication.append(row)print(multiplication)

Here, the nested for loop generates the same output as the nested list comprehension. We can see that the code with list comprehension is much cleaner and concise.

List Comprehensions vs Lambda Functions

Along with list comprehensions, we also use lambda functions to work with lists.

While list comprehension is commonly used for filtering a list based on some conditions, lambda functions are commonly used with functions like map() and filter().

They are used for complex operations or when an anonymous function is required.

Let's look at an example.

numbers = [5, 6, 7, 8, 9]

# create a new list using a lambda functionsquare_numbers = list(map(lambda num : num**2 , numbers))

print(square_numbers)

Output

[25, 36, 49, 64, 81]

We can achieve the same result using list comprehension by:

# create a new list using list comprehensionsquare_numbers = [num ** 2 for num in numbers]

If we compare the two codes, list comprehension is straightforward and simpler to read and understand.

So unless we need to perform complex operations, we can stick to list comprehension.

Visit Python Lambda/ Function to learn more about the use of lambda functions in Python.

Python List Comprehension (With Examples) (2024)

FAQs

What is list comprehension in Python with an example? ›

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

What are the 4 types of comprehension in Python? ›

There are four types of comprehension in Python for different data types – list comprehension, dictionary comprehension, set comprehension, and generator comprehension.

What is the difference between a list comprehension and a for loop in Python? ›

The for loop is a common way to iterate through a list. List comprehension, on the other hand, is a more efficient way to iterate through a list because it requires fewer lines of code. List comprehension requires less computation power than a for loop because it takes up less space and code.

Is list comprehension faster than for loop? ›

As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.

Is Python list comprehension lazy? ›

3 Answers. There's no lazy evaluation of lists in Python.

What is the main advantage of using list comprehensions in Python? ›

Advantages of Python List Comprehensions:
  • Conciseness and Readability. Python list comprehensions allow you to express complex operations on lists in a single line of code. ...
  • Efficiency. ...
  • Expressive Filtering and Mapping. ...
  • Versatility. ...
  • Limited Expressiveness. ...
  • Debugging Challenges.
Sep 10, 2023

Why is it called list comprehension Python? ›

In a list or set comprehension, instead of giving the elements of the list or set explicitly, the programmer is describing what they comprehend (in the "include" sense) with an expression. Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).

Why do we use comprehension in Python? ›

A comprehension is used like an operation on the data set (whether it is a list, dict, or set) that is generally a few lines of code and shrinks to a single or multiple lines, thereby increasing the readability and making the code compact.

What is the difference between set comprehension and list comprehension in Python? ›

The key aspect of set comprehension that makes it unique is that it returns a set, which means the elements inside will be unordered and cannot contain any duplicates. The rest is pretty much the same as a list comprehension. The input can be anything that contains a group of elements. Let's look at some examples.

When to not use list comprehension? ›

Now let's take three examples to understand why you shouldn't be using list comprehensions for tasks that require super complex expressions. Because in such cases, list comprehensions—instead of making your code elegant—make your code difficult to read and maintain.

What is the faster alternative to list comprehension? ›

If we use an existing function instead of a lambda, map() is faster than list comprehension. This time list comprehension is around 44% slower than map() (45.4/31.5≈1.44).

Why is list comprehension faster than map? ›

List comprehension returns a list, whereas the map function returns an object of Iterable. List comprehension execution is faster than that of map function when the formula expression is huge and complex. Map function is faster than list comprehension when the formula is already defined as a function earlier.

Can we write every loop as list comprehension? ›

Every comprehension of the list can be rewritten in for loop, but in the context of list interpretation, every for loop can not be rewritten.

Which is faster lambda or list comprehension? ›

List comprehensions are fastest, followed by filter() with a predefined filter function, and filter() with an ad-hoc lambda function comes in last.

What is the time complexity of list comprehension Python? ›

It's at least O(n) where n is the number of elements in the list you start out with. It could be worse complexity like if those elements were strings of size m and you're searching them for a letter, the complexity would be O(nm). It will change list comprehension to list comprehension.

What is mean using list comprehension in Python? ›

In Python, list comprehension is a method or construct that can be used to define and create a list from a string or another existing list. Besides creating lists, we can filter and transform data using list comprehension, which has a more human-readable and concise syntax.

What is the list comprehension operation in Python? ›

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The expressions can be any kind of Python object. List comprehensions will commonly take the form of [<value> for <vars> in <iter>] .

What is list in Python with example? ›

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ] .

Top Articles
Latest Posts
Article information

Author: Rev. Leonie Wyman

Last Updated:

Views: 6699

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Rev. Leonie Wyman

Birthday: 1993-07-01

Address: Suite 763 6272 Lang Bypass, New Xochitlport, VT 72704-3308

Phone: +22014484519944

Job: Banking Officer

Hobby: Sailing, Gaming, Basketball, Calligraphy, Mycology, Astronomy, Juggling

Introduction: My name is Rev. Leonie Wyman, I am a colorful, tasty, splendid, fair, witty, gorgeous, splendid person who loves writing and wants to share my knowledge and understanding with you.