The Ultimate Guide to Python Comprehensions: Sub-stack Edition
Beyond Lists: Exploring Other Python Comprehensions
Comprehension: In Python, comprehensions provide a concise way to create collections (like lists, dictionaries, sets, and tuples) by using a single line of code. Comprehensions can be used to apply operations, filter data, and create new collections with less code.
List Comprehension:
Definition: A list comprehension creates a new list by applying an expression to each item in an iterable.
# Syntax:
[expression for item in iterable if condition]
# Trick: Use list comprehension to flatten nested lists.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]&
2. Dictionary Comprehension:
Definition: A dictionary comprehension creates a new dictionary by applying an expression to each key-value pair in an iterable.
# Syntax:
{key_expression: value_expression for item in iterable if condition}
# Trick: Inverting keys and values in a dictionary.
original_dict = {'a': 1, 'b': 2, 'c': 3}
inverted_dict = {v: k for k, v in original_dict.items()}
# Output: {1: 'a', 2: 'b', 3: 'c'}
3. Set Comprehension:
Definition: A set comprehension creates a new set by applying an expression to each item in an iterable. Since sets automatically handle duplicates, this is a great way to ensure unique items.
# Syntax:
{expression for item in iterable if condition}
# Trick: Extract unique vowels from a string.
vowels = {char for char in 'pythoncomprehension' if char in 'aeiou'}
# Output: {'e', 'o', 'i'}
4. Tuple Comprehension (Generator Expression):
Definition: While Python does not have tuple comprehensions, you can create a tuple by using a generator expression, which is similar in syntax to a comprehension but uses parentheses instead of square brackets. This generates items one at a time and is more memory efficient.
# Syntax:
(expression for item in iterable if condition)
# Trick: Generate a sequence of tuples.
pairs = ((x, x**2) for x in range(5))
pairs_tuple = tuple(pairs)
# Output: ((0, 0), (1, 1), (2, 4), (3, 9), (4, 16))
Summary of Tricks:
List comprehension can be used to flatten nested lists.
Dictionary comprehension can invert keys and values.
Set comprehension automatically removes duplicates.
Tuple comprehension (via generator expressions) is memory efficient and can be converted to a tuple.
Great summary of Python tricks! I love how comprehensions make the code more efficient and readable. Especially excited to use tuple comprehension for memory efficiency