October 2018
Beginner to intermediate
466 pages
12h 2m
English
Comprehensions aren't restricted to lists. We can use a similar syntax with braces to create sets and dictionaries as well. Let's start with sets. One way to create a set is to wrap a list comprehension in the set() constructor, which converts it to a set. But why waste memory on an intermediate list that gets discarded, when we can create a set directly?
Here's an example that uses a named tuple to model author/title/genre triads, and then retrieves a set of all the authors that write in a specific genre:
from collections import namedtupleBook = namedtuple("Book", "author title genre")books = [ Book("Pratchett", "Nightwatch", "fantasy"), Book("Pratchett", "Thief Of Time", "fantasy"), Book("Le Guin", "The ...