Member-only story
The Ultimate Guide to Python Comprehensions: Medium Edition
Beyond Lists: Exploring Other Python Comprehensions
What is a comprehension in Python?
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'…









