This cheatsheet provides a quick reference for using comprehensions in Python, including list comprehensions, dictionary comprehensions, and how to incorporate conditional logic. Use this as a guide during your masterβs program to write more concise and readable code.
List Comprehensions
Basic Syntax
A list comprehension provides a concise way to create lists. The basic syntax is:
Code
# [expression for item in iterable]squares = [i **2for i inrange(1, 6)]print(squares)
[1, 4, 9, 16, 25]
With Conditional Logic
You can add a condition to include only certain items in the new list:
Code
# [expression for item in iterable if condition]even_squares = [i **2for i inrange(1, 6) if i %2==0]print(even_squares)
[4, 16]
Nested List Comprehensions
List comprehensions can be nested to handle more complex data structures:
Code
# [(expression1, expression2) for item1 in iterable1 for item2 in iterable2]pairs = [(i, j) for i inrange(1, 4) for j inrange(1, 3)]print(pairs)
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
Evaluating Functions in a List Comprehension
You can use list comprehensions to apply a function to each item in an iterable:
Code
# Function to evaluatedef square(x):return x **2# List comprehension applying the functionsquares = [square(i) for i inrange(1, 6)]print(squares)
[1, 4, 9, 16, 25]
Dictionary Comprehensions
Basic Syntax
Dictionary comprehensions provide a concise way to create dictionaries. The basic syntax is:
Code
# {key_expression: value_expression for item in iterable}# Example: Mapping fruit names to their lengthsfruits = ['apple', 'banana', 'cherry']fruit_lengths = {fruit: len(fruit) for fruit in fruits}print(fruit_lengths)
{'apple': 5, 'banana': 6, 'cherry': 6}
Without zip
You can create a dictionary without using zip by leveraging the index:
Code
# {key_expression: value_expression for index in range(len(list))}# Example: Mapping employee IDs to namesemployee_ids = [101, 102, 103]employee_names = ['Alice', 'Bob', 'Charlie']id_to_name = {employee_ids[i]: employee_names[i] for i inrange(len(employee_ids))}print(id_to_name)
{101: 'Alice', 102: 'Bob', 103: 'Charlie'}
With Conditional Logic
You can include conditions to filter out key-value pairs:
Code
# {key_expression: value_expression for item in iterable if condition}# Example: Filtering students who passedstudents = ['Alice', 'Bob', 'Charlie']scores = [85, 62, 90]passing_students = {students[i]: scores[i] for i inrange(len(students)) if scores[i] >=70}print(passing_students)
{'Alice': 85, 'Charlie': 90}
Evaluating Functions in a Dictionary Comprehension
You can use dictionary comprehensions to apply a function to values in an iterable:
Code
# Function to evaluatedef capitalize_name(name):return name.upper()# Example: Mapping student names to capitalized namesstudents = ['alice', 'bob', 'charlie']capitalized_names = {name: capitalize_name(name) for name in students}print(capitalized_names)
Keep It Simple: Use comprehensions for simple transformations and filtering. For complex logic, consider using traditional loops for better readability.
Nested Comprehensions: While powerful, nested comprehensions can be hard to read. Use them sparingly and consider breaking down the logic into multiple steps if needed.
Readability: Always prioritize code readability. If a comprehension is difficult to understand, it might be better to use a loop.