So far in our journey, we have already learned how to interact with files in Python to store data for extended periods. We also explored the core Python data structures, i.e., lists, tuples, dictionaries, and sets, and we know how to work with them. Traditionally, we populate these collections using 'for' loops and library functions like append()
and insert()
. Although this approach is functional, Python offers a more efficient, fast, and concise way to initialize these collections, i.e., Comprehensions.
Comprehensions are a shorthand way to add values to lists, dictionaries, and sets. In this article, you will learn how to use list and dictionary comprehensions and transform your code for data creation.
List Comprehensions
The list comprehension provides a simplified way to create lists from existing iterables, such as lists, tuples, and ranges. This is the most extensively used comprehension type.
Suppose we want a list of numbers squared in another list. Normally, we do that using the 'for' loop as follows:
numbers = [2,3,4,5,6]
squares = []
for number in numbers:
squares.append(number**2)
print(squares)
Although this is functional, it includes multiple lines with an explicit append()
call. So, a more efficient approach to achieve this would be list comprehension.
Syntax:
[expression for item in iterable if condition]
In the above syntax:
Expression
is the operation you want to perform on each item.Item
is the item in a range or a list.Condition
is optional. If you want the items to be added to the new list, if it confirms the condition, you can specify it.
Example:
Here's the above example rewritten using list comprehension:
numbers = [2,3,4,5,6]
squares = [number**2 for number in numbers] #sqaures each number and stores it in the squares list.
print(squares)
Output:
[4, 9, 16, 25, 36]
Here are some more example programs for your understanding:
# Converting strings to uppercase
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
List Comprehensions with 'if'
When you want the items to be added in the new list based on a certain condition, you can use the 'if' statement as follows:
numbers = [1,2,3,4,5,6,7,8,9,10]
evens = [i for i in range(len(numbers)) if i%2 == 0]
print("Even numbers: ")
print(evens)
The above program adds the number in the 'evens' list if the number divided by 2 leaves a 0 remainder.
List Comprehensions with 'if-else'
If you want to add one item in the list if the condition is true and another if it is false, you can incorporate the if-else statement in list comprehension.
numbers = [1,2,3,4,5,6,7,8,9,10]
evens = ["Even" if i%2 == 0 else "Odd" for i in range(len(numbers))]
print(evens)
Dictionary Comprehensions
Just like list comprehensions, dictionary comprehensions allow you to create new dictionaries. This is a shorthand way to create dictionaries.
Suppose we want to create a dictionary of squares from another dictionary. We want to use the actual number as the key and its square as its value. Traditionally, we will do that as follows:
numbers = {1:1, 2:2, 3:3, 4:4, 5:5}
squares = {}
for key, value in numbers.items(): # Getting keys and values from the first dictionary
squares[key] = value ** 2 # Associating each key with its squared value
print(squares)
The above approach is entirely fine, but it comprises multiple lines and appears somewhat complex. To simplify this, we use dictionary comprehension.
Syntax:
{key_expression: value_expression for item in iterable if condition}
In the above syntax:
key_expression
refers to the key evaluation.value_expression
refers to the value evaluation.item
- represents the iterable or an item in the existing dictionary.Condition
- is totally optional. If you want to add items to the dictionary based on specific conditions, you can specify them here.
Example:
Let's rewrite the above code using dictionary comprehension:
numbers = {1:1, 2:2, 3:3, 4:4, 5:5}
squares = {key: value ** 2 for key, value in numbers.items()} # Assigns the squared value to the key for each item in the numbers dictionary.
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionary Comprehensions with 'if'
If you want to evaluate a condition before an item is added to a dictionary, you can use the 'if' statement with dictionary comprehension.
numbers = {1:1, 2:2, 3:3, 4:4, 5:5}
squares = {key: value ** 2 for key, value in numbers.items() if value % 2 == 0} # Only even numbers are added to the dictionary
print(squares)
Congratulations! You have added another powerful tool to your Python arsenal, i.e., comprehensions. They allow you to transform and create new data structures with high readability and efficiency, replacing the multiline loops. You can achieve more with less code using comprehensions. Hopefully, you are enjoying this Python venture so far with me. In the next article, we will get ourselves equipped with generators and iterators to handle larger data streams and sequences efficiently.