Online Book Reader

Home Category

Learning Python - Mark Lutz [93]

By Root 1711 0
we previewed in Chapter 4, but is coded in curly braces instead of square brackets and run to make a set instead of a list. Set comprehensions run a loop and collect the result of an expression on each iteration; a loop variable gives access to the current iteration value for use in the collection expression. The result is a new set created by running the code, with all the normal set behavior:

>>> {x ** 2 for x in [1, 2, 3, 4]} # 3.0 set comprehension

{16, 1, 4, 9}

In this expression, the loop is coded on the right, and the collection expression is coded on the left (x ** 2). As for list comprehensions, we get back pretty much what this expression says: “Give me a new set containing X squared, for every X in a list.” Comprehensions can also iterate across other kinds of objects, such as strings (the first of the following examples illustrates the comprehension-based way to make a set from an existing iterable):

>>> {x for x in 'spam'} # Same as: set('spam')

{'a', 'p', 's', 'm'}

>>> {c * 4 for c in 'spam'} # Set of collected expression results

{'ssss', 'aaaa', 'pppp', 'mmmm'}

>>> {c * 4 for c in 'spamham'}

{'ssss', 'aaaa', 'hhhh', 'pppp', 'mmmm'}

>>> S = {c * 4 for c in 'spam'}

>>> S | {'mmmm', 'xxxx'}

{'ssss', 'aaaa', 'pppp', 'mmmm', 'xxxx'}

>>> S & {'mmmm', 'xxxx'}

{'mmmm'}

Because the rest of the comprehensions story relies upon underlying concepts we’re not yet prepared to address, we’ll postpone further details until later in this book. In Chapter 8, we’ll meet a first cousin in 3.0, the dictionary comprehension, and I’ll have much more to say about all comprehensions (list, set, dictionary, and generator) later, especially in Chapters14 and 20. As we’ll learn later, all comprehensions, including sets, support additional syntax not shown here, including nested loops and if tests, which can be difficult to understand until you’ve had a chance to study larger statements.

Why sets?

Set operations have a variety of common uses, some more practical than mathematical. For example, because items are stored only once in a set, sets can be used to filter duplicates out of other collections. Simply convert the collection to a set, and then convert it back again (because sets are iterable, they work in the list call here):

>>> L = [1, 2, 1, 3, 2, 4, 5]

>>> set(L)

{1, 2, 3, 4, 5}

>>> L = list(set(L)) # Remove duplicates

>>> L

[1, 2, 3, 4, 5]

Sets can also be used to keep track of where you’ve already been when traversing a graph or other cyclic structure. For example, the transitive module reloader and inheritance tree lister examples we’ll study in Chapters 24 and 30, respectively, must keep track of items visited to avoid loops. Although recording states visited as keys in a dictionary is efficient, sets offer an alternative that’s essentially equivalent (and may be more or less intuitive, depending on who you ask).

Finally, sets are also convenient when dealing with large data sets (database query results, for example)—the intersection of two sets contains objects in common to both categories, and the union contains all items in either set. To illustrate, here’s a somewhat more realistic example of set operations at work, applied to lists of people in a hypothetical company, using 3.0 set literals (use set in 2.6):

>>> engineers = {'bob', 'sue', 'ann', 'vic'}

>>> managers = {'tom', 'sue'}

>>> 'bob' in engineers # Is bob an engineer?

True

>>> engineers & managers # Who is both engineer and manager?

{'sue'}

>>> engineers | managers # All people in either category

{'vic', 'sue', 'tom', 'bob', 'ann'}

>>> engineers – managers # Engineers who are not managers

{'vic', 'bob', 'ann'}

>>> managers – engineers # Managers who are not engineers

{'tom'}

>>> engineers > managers # Are all managers engineers? (superset)

False

>>> {'bob', 'sue'} < engineers # Are both engineers? (subset)

True

>>> (managers | engineers) > managers # All people is a superset of managers

True

>>> managers ^ engineers # Who is in one but not both?

{'vic', 'bob', 'ann', 'tom'}

>>>

Return Main Page Previous Page Next Page

®Online Book Reader