Python Comprehensions - Summary Notes
1. Introduction to Comprehensions
Comprehensions offer a cleaner, more readable way to create data collections. They replace verbose
for-loops with one-liner expressions.
2. List Comprehensions
Syntax: [expression for item in iterable]
Example 1: Copying a List
nums = [1, 2, 3, 4, 5]
my_list = [n for n in nums]
Example 2: Squaring Elements
squares = [n * n for n in nums]
Example 3: Filtering with Conditionals
evens = [n for n in nums if n % 2 == 0]
Example 4: Nested Loops for Pair Combinations
pairs = [(letter, num) for letter in 'ABCD' for num in range(4)]
3. Dictionary Comprehensions
Syntax: {key_expr: value_expr for item in iterable}
Example:
{name: hero for name, hero in zip(names, heroes)}
4. Set Comprehensions
Syntax: {expression for item in iterable}
Example:
Python Comprehensions - Summary Notes
unique = {n for n in nums}
5. Generator Expressions
Syntax: (expression for item in iterable)
Example:
squares = (n * n for n in nums)
6. Summary Table
List: [n * n for n in nums] - stores all results
Set: {n for n in nums} - unique values only
Dict: {k: v for k, v in zip(keys, vals)} - key-value mapping
Generator: (n * n for n in nums) - memory efficient
7. Takeaways
- Reduces boilerplate code
- Enhances clarity and performance
- Use [] for lists, {} for sets/dicts, () for generators
- Replace map/filter with comprehensions for readability