Comprehension with Sequences#
In this tutorial, we will focus on comprehension, a powerful feature in Python that allows us to create and manipulate lists, sets, and dictionaries in a concise and efficient manner. To make this tutorial relatable for humanists, we will use examples from J.R.R. Tolkien’s ‘The Hobbit.’
What is Comprehension?#
Comprehension allows you to generate new data structures by applying an expression to each item in an existing iterable (e.g., a list, a set, or a range) while optionally filtering the items based on a condition. Comprehensions make your code more readable and often faster.
There are three main types of comprehension in Python:
List Comprehension: It creates a new list by applying an expression to each element in an existing iterable. The syntax for list comprehension is:
[expression for item in iterable if condition]
Set Comprehension: Similar to list comprehension, it creates a new set instead of a list. The syntax for set comprehension is:
{expression for item in iterable if condition}
Dictionary Comprehension: It creates a new dictionary by applying an expression that generates key-value pairs for each element in an existing iterable. The syntax for dictionary comprehension is:
{key_expression: value_expression for item in iterable if condition}
Here is a handy table that you can refer to:
Comprehension Type |
Syntax |
Example |
---|---|---|
List Comprehension |
|
|
Set Comprehension |
|
|
Dictionary Comprehension |
|
|
In each type of comprehension, the expression is applied to each item in the iterable. The optional if condition part allows you to filter the items based on a specific condition.
Comprehension provides a more elegant and readable alternative to traditional loops and conditional statements when creating and manipulating data structures in Python.
In this tutorial, we will learn about each of these.
List Comprehension#
Here again is the synytax for
characters = ["Bilbo", "Gandalf", "Thorin", "Balin", "Dwalin", "Kili", "Fili"]
lower_case_characters = [name.lower() for name in characters]
print(lower_case_characters)
['bilbo', 'gandalf', 'thorin', 'balin', 'dwalin', 'kili', 'fili']
Set Comprehension#
Set comprehension works similarly to list comprehension but creates a set instead of a list. It uses curly braces {} instead of square brackets.
name_lengths = {len(name) for name in characters}
print(name_lengths)
{4, 5, 6, 7}
Dictionary Comprehension#
Dictionary comprehension allows us to create dictionaries with a concise syntax. It consists of a key-value pair expression followed by a ‘for’ statement inside curly braces.
name_length_dict = {name: len(name) for name in characters}
print(name_length_dict)
{'Bilbo': 5, 'Gandalf': 7, 'Thorin': 6, 'Balin': 5, 'Dwalin': 6, 'Kili': 4, 'Fili': 4}
Combining Comprehension with Conditionals#
We can also add a condition using an if
statement. Let’s say, we only wanted the names that were longer than 5 characters. We could add the if statement at the end of our condition.
long_names = [name for name in characters if len(name) > 5]
print(long_names)
['Gandalf', 'Thorin', 'Dwalin']
We can even alter our syntax to express an if
and else
condition. In this example, we used an if-else expression within the list comprehension:
"hobbit" if name == "Bilbo" else "non-hobbit"
: This expression checks if the character’s name is “Bilbo” and assigns the value “hobbit” if the condition is met. Otherwise, it assigns the value “non-hobbit”.for name in characters
: This iterates over each element (name) in the characters list.
The resulting list, category, stores the character classification as either “hobbit” or “non-hobbit”.In this example, we used an if-else expression within the list comprehension:
category = ["hobbit" if name == "Bilbo" else "non-hobbit" for name in characters]
print(category)
['hobbit', 'non-hobbit', 'non-hobbit', 'non-hobbit', 'non-hobbit', 'non-hobbit', 'non-hobbit']
By now, you should have a better understanding of comprehension in Python and how it can be applied to lists, sets, and dictionaries. With these examples from ‘The Hobbit,’ you can start experimenting and creating your own comprehension expressions to analyze and manipulate data from your favorite literary works