List Comprehensions β
π What are List Comprehensions? β
List comprehensions provide a concise way to create lists based on existing iterables. They're more readable and often faster than traditional loops.
Basic Syntax β
python
# Basic syntax: [expression for item in iterable]
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Traditional approach (more verbose)
squares_traditional = []
for x in range(10):
squares_traditional.append(x**2)
print(squares_traditional) # Same resultWith Conditional Filtering β
python
# Syntax: [expression for item in iterable if condition]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# Multiple conditions
positive_odds = [x for x in range(-10, 11) if x > 0 and x % 2 == 1]
print(positive_odds) # [1, 3, 5, 7, 9]π Basic List Comprehensions β
Simple Transformations β
python
# String operations
words = ["hello", "world", "python", "code"]
uppercase = [word.upper() for word in words]
print(uppercase) # ['HELLO', 'WORLD', 'PYTHON', 'CODE']
# String lengths
lengths = [len(word) for word in words]
print(lengths) # [5, 5, 6, 4]
# Mathematical operations
numbers = [1, 2, 3, 4, 5]
cubes = [x**3 for x in numbers]
print(cubes) # [1, 8, 27, 64, 125]
# Working with functions
import math
angles = [0, 30, 45, 60, 90]
radians = [math.radians(angle) for angle in angles]
print(radians) # [0.0, 0.5236, 0.7854, 1.0472, 1.5708]Filtering with Conditions β
python
# Filter positive numbers
numbers = [-5, -2, 0, 3, 7, -1, 4]
positive = [x for x in numbers if x > 0]
print(positive) # [3, 7, 4]
# Filter strings by length
words = ["cat", "elephant", "dog", "hippopotamus", "ant"]
long_words = [word for word in words if len(word) > 3]
print(long_words) # ['elephant', 'hippopotamus']
# Filter and transform
even_doubles = [x * 2 for x in range(10) if x % 2 == 0]
print(even_doubles) # [0, 4, 8, 12, 16]π Nested List Comprehensions β
Working with 2D Lists β
python
# Create a 2D matrix
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# Flatten a 2D list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Transpose a matrix
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]Multiple Iterations β
python
# Cartesian product
colors = ['red', 'blue']
sizes = ['S', 'M', 'L']
combinations = [f"{color}-{size}" for color in colors for size in sizes]
print(combinations) # ['red-S', 'red-M', 'red-L', 'blue-S', 'blue-M', 'blue-L']
# Multiplication table
multiplication_table = [f"{i} x {j} = {i*j}" for i in range(1, 4) for j in range(1, 4)]
for item in multiplication_table:
print(item)π― Conditional Expressions β
if-else in List Comprehensions β
python
# Syntax: [expression_if_true if condition else expression_if_false for item in iterable]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_odd = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(even_odd) # ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
# Apply different operations based on condition
processed = [x**2 if x % 2 == 0 else x**3 for x in range(1, 6)]
print(processed) # [1, 4, 27, 16, 125]
# Grade assignment
scores = [85, 92, 78, 96, 88, 73, 91]
grades = ["A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F" for score in scores]
print(grades) # ['B', 'A', 'B', 'A', 'B', 'C', 'A']π§ Set and Dictionary Comprehensions β
Set Comprehensions β
python
# Create sets using comprehension
numbers = [1, 2, 2, 3, 3, 4, 5]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # {1, 4, 9, 16, 25}
# Filter vowels from a string
text = "hello world"
vowels = {char for char in text if char in 'aeiou'}
print(vowels) # {'e', 'o'}Dictionary Comprehensions β
python
# Create dictionary from lists
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Square dictionary
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filter dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
filtered_dict = {k: v for k, v in original_dict.items() if v % 2 == 0}
print(filtered_dict) # {'b': 2, 'd': 4}
# Transform dictionary values
word_lengths = {word: len(word) for word in ['apple', 'banana', 'cherry']}
print(word_lengths) # {'apple': 5, 'banana': 6, 'cherry': 6}π Practice Examples β
Example 1: Data Processing β
python
# Process student data
students = [
{'name': 'Alice', 'age': 20, 'grades': [85, 92, 78]},
{'name': 'Bob', 'age': 19, 'grades': [88, 76, 91]},
{'name': 'Charlie', 'age': 21, 'grades': [92, 88, 84]},
{'name': 'Diana', 'age': 20, 'grades': [95, 87, 92]}
]
# Calculate average grades
averages = {student['name']: sum(student['grades']) / len(student['grades'])
for student in students}
print(averages)
# Find students with high averages
high_performers = [student['name'] for student in students
if sum(student['grades']) / len(student['grades']) >= 85]
print(high_performers)
# Create age groups
age_groups = {student['name']: 'adult' if student['age'] >= 21 else 'minor'
for student in students}
print(age_groups)Example 2: Text Processing β
python
# Analyze text
text = "The quick brown fox jumps over the lazy dog"
words = text.lower().split()
# Word lengths
word_lengths = {word: len(word) for word in words}
print(word_lengths)
# Filter words by length
long_words = [word for word in words if len(word) > 4]
print(long_words)
# First letter of each word
first_letters = [word[0] for word in words]
print(first_letters)
# Count vowels in each word
vowel_counts = {word: sum(1 for char in word if char in 'aeiou')
for word in words}
print(vowel_counts)Example 3: Mathematical Operations β
python
# Create multiplication table
multiplication_table = {f"{i}x{j}": i*j for i in range(1, 11) for j in range(1, 11)}
# Print 5x table
five_table = {k: v for k, v in multiplication_table.items() if k.startswith('5x')}
print(five_table)
# Prime numbers (simple approach)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [x for x in range(2, 100) if is_prime(x)]
print(primes[:10]) # First 10 primes
# Perfect squares
perfect_squares = [x for x in range(1, 101) if int(x**0.5)**2 == x]
print(perfect_squares)Example 4: File Processing β
python
# Simulate file data
log_entries = [
"2023-01-01 10:00:00 INFO User logged in",
"2023-01-01 10:05:00 ERROR Database connection failed",
"2023-01-01 10:10:00 INFO User logged out",
"2023-01-01 10:15:00 WARNING Low disk space",
"2023-01-01 10:20:00 ERROR Authentication failed"
]
# Extract error messages
errors = [entry for entry in log_entries if "ERROR" in entry]
print("Errors:", errors)
# Extract timestamps
timestamps = [entry.split()[1] for entry in log_entries]
print("Timestamps:", timestamps)
# Create log level counts
log_levels = [entry.split()[2] for entry in log_entries]
level_counts = {level: log_levels.count(level) for level in set(log_levels)}
print("Log level counts:", level_counts)
# Parse structured data
parsed_logs = [
{
'date': entry.split()[0],
'time': entry.split()[1],
'level': entry.split()[2],
'message': ' '.join(entry.split()[3:])
}
for entry in log_entries
]
for log in parsed_logs:
print(f"{log['time']} [{log['level']}]: {log['message']}")β‘ Performance Comparison β
python
import time
# Compare list comprehension vs traditional loop
def time_comparison():
# List comprehension
start = time.time()
squares_comp = [x**2 for x in range(100000)]
comp_time = time.time() - start
# Traditional loop
start = time.time()
squares_loop = []
for x in range(100000):
squares_loop.append(x**2)
loop_time = time.time() - start
print(f"List comprehension: {comp_time:.4f} seconds")
print(f"Traditional loop: {loop_time:.4f} seconds")
print(f"Comprehension is {loop_time/comp_time:.2f}x faster")
time_comparison()π― Best Practices β
When to Use List Comprehensions β
python
# Good: Simple transformations
squares = [x**2 for x in range(10)]
# Good: Simple filtering
evens = [x for x in range(10) if x % 2 == 0]
# Avoid: Complex logic (use regular loops instead)
# Bad example:
# complex_result = [do_something(x) if complex_condition(x) else do_other_thing(x)
# for x in items if another_complex_condition(x)]
# Better: Use regular function
def process_items(items):
result = []
for x in items:
if another_complex_condition(x):
if complex_condition(x):
result.append(do_something(x))
else:
result.append(do_other_thing(x))
return resultReadability Guidelines β
python
# Good: One line, clear intent
names = [person['name'] for person in people]
# Acceptable: Multiple lines for complex expressions
filtered_data = [
process_item(item)
for item in data
if item.is_valid() and item.priority > 5
]
# Consider regular loops for very complex logicπ― Key Takeaways β
- List comprehensions are concise and often faster than loops
- Basic syntax:
[expression for item in iterable] - With filtering:
[expression for item in iterable if condition] - Conditional expressions:
[expr1 if condition else expr2 for item in iterable] - Set comprehensions:
{expression for item in iterable} - Dictionary comprehensions:
{key: value for item in iterable} - Nested comprehensions can handle complex data structures
- Use for simple transformations and filtering
- Avoid for complex logic - use regular loops instead
- List comprehensions are more Pythonic and readable when used appropriately
Continue to: Python Tools β