Python: Comprehensions

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

Build a list with a list comprehension

import string

alphabet = string.ascii_lowercase
alphabet_list = [letter for letter in alphabet]

print(alphabet_list)

Build 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)

Build a set with a set comprehension

import string

alphabet = string.ascii_lowercase
even_number_set = {letter: num for num, letter in alphabet and enumerate(alphabet) if num % 2 == 0}

print(even_number_set)

About the author

Shane Bellone

At the intersection of capricious and whimsy.

Add comment

By Shane Bellone