Command Palette

Search for a command to run...

Comprehensions

Write concise and readable code with list, dictionary, and set comprehensions

List Comprehensions

  • Create lists in a single line of code
  • More readable and faster than traditional loops
  • Syntax: [expression for item in iterable if condition]
  • Can include conditional logic
# Basic list comprehension
squares = [x ** 2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens)  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# String manipulation
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON']

# Nested comprehension
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix)  # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Dictionary Comprehensions

  • Create dictionaries with concise syntax
  • Syntax: {key: value for item in iterable if condition}
  • Useful for transforming or filtering dictionaries
  • Can also combine multiple lists into a dictionary
# Basic dictionary comprehension
squares_dict = {x: x ** 2 for x in range(6)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# From two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict)  # {'a': 1, 'b': 2, 'c': 3}

# With condition (filtering values)
nums = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered = {k: v for k, v in nums.items() if v > 2}
print(filtered)  # {'c': 3, 'd': 4}

# Transform values
prices = {"apple": 0.5, "banana": 0.3}
doubled = {k: v * 2 for k, v in prices.items()}
print(doubled)  # {'apple': 1.0, 'banana': 0.6}

Set Comprehensions

  • Create sets with unique elements
  • Syntax: {expression for item in iterable if condition}
  • Automatically removes duplicates
  • Useful for extracting unique values
# Basic set comprehension
unique_squares = {x ** 2 for x in range(-5, 6)}
print(unique_squares)  # {-5^2 ... 5^2} => {0, 1, 4, 9, 16, 25}

# Remove duplicates from list
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique = {x for x in numbers}
print(unique)  # {1, 2, 3, 4}

# With condition
text = "hello world"
vowels = {char for char in text if char in "aeiou"}
print(vowels)  # {'o', 'e'}

Generator Expressions

  • Similar to list comprehensions but use parentheses
  • Memory efficient – generate values on-the-fly
  • Don't create entire list in memory
  • Useful for working with large datasets
# Generator expression
gen = (x ** 2 for x in range(10))
print(type(gen))  # <class 'generator'>

# Iterate through generator
for value in gen:
    print(value, end=" ")
# Output: 0 1 4 9 16 25 36 49 64 81

# Use in functions
total = sum(x ** 2 for x in range(100))
print(f"\nSum: {total}")  # Sum: 328350

# Memory efficient for large data
large_gen = (x for x in range(1000000))
first_five = [next(large_gen) for _ in range(5)]
print(first_five)  # [0, 1, 2, 3, 4]