python
  1. python-list-comprehension

Python List Comprehension

List comprehension is a concise way to create lists based on existing lists or iterables. It is a more elegant and efficient way to create lists in Python as compared to traditional loops.

Syntax

new_list = [expression for item in iterable if condition]
  • expression: The operation or value to be stored in the new list.
  • item: The variable representing a single item from the iterable.
  • iterable: The collection being iterated over.
  • condition (optional): The conditional expression used to filter items.

Example

Suppose we have a list of numbers and we want to create a new list with only the even numbers in the original list. We can use a traditional loop as follows:

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

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(even_numbers)

Output:

[2, 4, 6, 8, 10]

The same result can be achieved using list comprehension in a more concise and efficient way:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)

Output:

[2, 4, 6, 8, 10]

Explanation

In the above example, we used list comprehension to create a new list called even_numbers that only contains even numbers from the numbers list.

We started with the expression num which represents each number in the numbers list. Then, we used the condition if num % 2 == 0 to check if num is even. If the condition is true, num is added to the even_numbers list using the append() method.

The same code can be written using list comprehension in a shorter and more readable way.

Use

List comprehension can be used to:

  • Create a new list containing specific values from an existing list.
  • Modify an existing list and create a new list based on the modified one.
  • Create a new list based on the values of multiple lists.

It is useful when you want to perform a single operation on all the elements of an iterable and create a new list with the result.

Important Points

  • List comprehension can be used with any iterable, not just lists.
  • The conditional expression is optional.
  • Multiple conditions can be used in one list comprehension.
  • Nested list comprehensions can be used to create a list of lists.

Summary

In this tutorial, we learned about Python List Comprehension, its syntax, and how it can be used to create a new list. We also saw some examples and discussed the important points to keep in mind while using list comprehension in Python.

Published on: