List Comprehension

List comprehension is an elegant way to define and create lists based on existing lists in Python. It can be used to create a new list from an existing one by specifying instructions on how to transform its elements, and also allows you to filter out items from the original list.

Syntax

The typical syntax for list comprehension in Python is as follows:

1new_list = [expression for item in iterable if condition]

Here is what each segment represents:

  1. expression: Transforms the item before it is added to the new list.
  2. iterable: Any object you can iterate over.
  3. condition (Optional): An optional condition that must be met for an item to be included in the new list.

Example

Let’s look at an example where we want to create a new list of squares for all numbers in an existing list.

1numbers = [1, 2, 3, 4, 5]
2squares = [number**2 for number in numbers]
3print(squares)

Output:

[1, 4, 9, 16, 25]

Here, the expression is number**2, the iterable is numbers and there is no condition.

We can also apply a condition to filter items from the original list. For instance, we can create a list of squares for only the even numbers in our original list:

1numbers = [1, 2, 3, 4, 5]
2even_squares = [number**2 for number in numbers if number % 2 == 0]
3print(even_squares)

Output:

[4, 16]

Here, the condition is number % 2 == 0, which verifies if a number is even.

Note

You can also use list comprehension with other iterables such as strings, tuples, and dictionaries.