Advanced Python - VI
Comprehensions in Python
Comprehensions in Python are concise ways to create new sequences like lists or dictionaries based on existing iterables. They transform an iterative for-loop into a single readable expression.
Advantages of Comprehensions
- More time-efficient and space-efficient than regular loops
- Require fewer lines of code
- Turn iterative logic into a clean, readable “formula”
Syntax of List Comprehension
new_list = [expression(element) for element in iterable if condition]
-
expression(element) → the operation applied to each element
-
iterable → the collection you loop over (list, string, etc.)
-
condition → optional filter that selects which elements to include
Examples of List Comprehensions
Example 1 – Squaring Numbers
# Square each number from 1 to 5
squares = [n ** 2 for n in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
Example 2 – Filtering Words
# Keep words longer than 3 letters
words = ["hi", "hello", "bye", "morning", "sun"]
long_words = [w for w in words if len(w) > 3]
print(long_words)
Output:
['hello', 'morning']
Example 3 – Creating a Matrix
# Generate a 4x4 matrix with row indices as values
matrix = [[row for row in range(4)] for col in range(4)]
print(matrix)
Output:
[[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3],
[0, 1, 2, 3]]
List Comprehension vs Traditional For Loop
Traditional For Loop
# Create a list of characters from a string
letters = []
for ch in "Python Rocks!":
letters.append(ch)
print(letters)
Output:
['P', 'y', 't', 'h', 'o', 'n', ' ', 'R', 'o', 'c', 'k', 's', '!']
List Comprehension Approach
letters = [ch for ch in "Python Rocks!"]
print(letters)
Output:
['P', 'y', 't', 'h', 'o', 'n', ' ', 'R', 'o', 'c', 'k', 's', '!']
👌Much shorter and clearer!
Dictionary Comprehensions
Like lists, you can also use dictionary comprehensions. The syntax looks like this:
new_dict = {key_expr: value_expr for item in iterable if condition}
Example – Dictionary Comprehension
# Create a dictionary mapping letters to their ASCII codes
letters = ['a', 'b', 'c', 'd']
ascii_dict = {letter: ord(letter) for letter in letters}
print(ascii_dict)
Output:
{'a': 97, 'b': 98, 'c': 99, 'd': 100}
Example – Filtering with Dictionary Comprehension
# Keep only items where the value is greater than 10
prices = {'apple': 5, 'banana': 12, 'cherry': 20, 'date': 7}
high_prices = {fruit: price for fruit, price in prices.items() if price > 10}
print(high_prices)
Output:
{'banana': 12, 'cherry': 20}
Creating a Dictionary from Two Lists
Another common usage:
# Create a dictionary from two lists
keys = ['cat', 'dog', 'bird']
values = ['meow', 'bark', 'tweet']
animal_sounds = {k: v for k, v in zip(keys, values)}
print(animal_sounds)
Output:
{'cat': 'meow', 'dog': 'bark', 'bird': 'tweet'}
👀Comprehensions are an incredibly powerful feature in Python that make your code shorter, faster, and more elegant.
Comments
Post a Comment