About 1545 letters

About 8 minutes

#Python's comprehensions

Comprehensions provide a concise syntax for creating containers.

#List Comprehension

For example, to create a list of length 10 with elements as x², we could use a loop:

numbers: list[int] = []
for x in range(10):
    numbers.append(x**2)
print(numbers)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

But this is a bit verbose. A comprehension makes it simpler:

# List comprehension
numbers: list[int] = [x**2 for x in range(10)]
print(numbers)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

  • The expression x**2 defines the value of each element
  • The loop for x in range(10) assigns values to x

Comprehensions can also use nested loops, for example to generate a multiplication table:

# List comprehension
numbers: list[int] = [x*y for x in range(1, 10) for y in range(1, 10)]
print(numbers)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Set and Dictionary Comprehensions

Sets and dictionaries can also be created with comprehensions:

# Set comprehension
numbers_set: set[int] = {x**2 for x in range(10)}
print(numbers_set)

# Dictionary comprehension
numbers_dict: dict[int] = {x: x**2 for x in range(10)}
print(numbers_dict)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Tuple Comprehension

Tuples do not support comprehensions directly, because parentheses () are used for generators. However, you can use the tuple() function to convert a generator into a tuple.

# Attempting a tuple comprehension
numbers: tuple[int] = (x**2 for x in range(10))
print(numbers)
print(tuple(numbers))    # Convert generator to tuple

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025