Published on

How to Use `List Comprehensions` in Python

Authors
  • avatar
    Name
    hwahyeon
    Twitter

list comprehension is a syntax in Python that allows you to create lists in a concise way. It can replace multiple lines of code that use for loops and if conditions with a single line. This makes it easier to read and write code for generating lists.

Basic Syntax

[expression for item in iterable if condition]
  • expression: The operation performed on each item (e.g., squaring the item or performing a calculation)
  • item: Each element in the iteration
  • iterable: An object that can be iterated over, such as a list, tuple, or string
  • condition (optional): A condition that each item must meet to be included in the list

Example

  1. Storing the squares of even numbers from a given list in a new list:
numbers = [1, 2, 3, 4, 5]
squares_of_even = [n**2 for n in numbers if n % 2 == 0]
# Result: [4, 16] (squares of 2 and 4)
  1. Comparison with a traditional for loop:
# Using a regular for loop
squares_of_even = []
for n in numbers:
    if n % 2 == 0:
        squares_of_even.append(n**2)

The for loop code above is longer and may be harder to read compared to the list comprehension.