Instagram
youtube
Facebook
Twitter

List Comprehension in Python

List comprehension is a concise and powerful way to create lists in Python. It allows us to create a new list by applying an expression to each item in an existing iterable and optionally filtering the items based on a condition.

In this tutorial, we'll learn about how to use list comprehension in Python with some examples.

Basic Syntax

List comprehensions consist of the following components:

new_list = [expression for item in iterable if condition]
  • new_list: The resulting list.

  • expression: An operation to perform on each item.

  • item: A variable representing an item in the iterable.

  • iterable: The source of items (e.g., a list or range).

  • condition (optional): A filter to include only specific items.

Examples

Example 1: Creating a list of squares.

squares = [x**2 for x in range(1, 6)]
print(squares)
  • ​​​​​​​The iterable is a range from 1 to 5.

  • The expression is x**2, which squares each number.

  • There is no condition, so all items from the range are included.

Output:

[1, 4, 9, 16, 25]

 

Example 2: Filtering even numbers.

squares = [x**2 for x in range(1, 6)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
  • The iterable is a list of numbers.

  • The expression is x, which keeps the number as is.

  • The condition checks if the number is even.

Output:

[1, 4, 9, 16, 25]