Python: Comprehensions

Comprehensions build data structures with one or more iterator. This approach reduces syntax and increase efficiency when building lists, dictionaries, or sets from conditional and loop statements.

Comprehension Examples

# Construct a list with a list comprehension
import string

alphabet = string.ascii_lowercase
alphabet_list = [letter for letter in alphabet]
print(alphabet_list)
# Construct a dictionary with a dictionary comprehension
import string

alphabet = string.ascii_lowercase
alphabet_list = {letter: num for num, letter in alphabet and enumerate(alphabet)}
print(alphabet_list)
# Construct a set with a set comprehension
import string

alphabet = string.ascii_lowercase
alphabet_list = {num for num, letter in alphabet and enumerate(alphabet)}
print(alphabet_list)

About the author

Shane Bellone

At the intersection of capricious and whimsy.

Add comment

By Shane Bellone