Online Book Reader

Home Category

Learning Python - Mark Lutz [92]

By Root 1433 0
to provide quick and standard operation.

Set literals in Python 3.0

If you think sets are “cool,” they recently became noticeably cooler. In Python 3.0 we can still use the set built-in to make set objects, but 3.0 also adds a new set literal form, using the curly braces formerly reserved for dictionaries. In 3.0, the following are equivalent:

set([1, 2, 3, 4]) # Built-in call

{1, 2, 3, 4} # 3.0 set literals

This syntax makes sense, given that sets are essentially like valueless dictionaries—because a set’s items are unordered, unique, and immutable, the items behave much like a dictionary’s keys. This operational similarity is even more striking given that dictionary key lists in 3.0 are view objects, which support set-like behavior such as intersections and unions (see Chapter 8 for more on dictionary view objects).

In fact, regardless of how a set is made, 3.0 displays it using the new literal format. The set built-in is still required in 3.0 to create empty sets and to build sets from existing iterable objects (short of using set comprehensions, discussed later in this chapter), but the new literal is convenient for initializing sets of known structure:

C:\Misc> c:\python30\python

>>> set([1, 2, 3, 4]) # Built-in: same as in 2.6

{1, 2, 3, 4}

>>> set('spam') # Add all items in an iterable

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

>>> {1, 2, 3, 4} # Set literals: new in 3.0

{1, 2, 3, 4}

>>> S = {'s', 'p', 'a', 'm'}

>>> S.add('alot')

>>> S

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

All the set processing operations discussed in the prior section work the same in 3.0, but the result sets print differently:

>>> S1 = {1, 2, 3, 4}

>>> S1 & {1, 3} # Intersection

{1, 3}

>>> {1, 5, 3, 6} | S1 # Union

{1, 2, 3, 4, 5, 6}

>>> S1 - {1, 3, 4} # Difference

{2}

>>> S1 > {1, 3} # Superset

True

Note that {} is still a dictionary in Python. Empty sets must be created with the set built-in, and print the same way:

>>> S1 - {1, 2, 3, 4} # Empty sets print differently

set()

>>> type({}) # Because {} is an empty dictionary

>>> S = set() # Initialize an empty set

>>> S.add(1.23)

>>> S

{1.23}

As in Python 2.6, sets created with 3.0 literals support the same methods, some of which allow general iterable operands that expressions do not:

>>> {1, 2, 3} | {3, 4}

{1, 2, 3, 4}

>>> {1, 2, 3} | [3, 4]

TypeError: unsupported operand type(s) for |: 'set' and 'list'

>>> {1, 2, 3}.union([3, 4])

{1, 2, 3, 4}

>>> {1, 2, 3}.union({3, 4})

{1, 2, 3, 4}

>>> {1, 2, 3}.union(set([3, 4]))

{1, 2, 3, 4}

>>> {1, 2, 3}.intersection((1, 3, 5))

{1, 3}

>>> {1, 2, 3}.issubset(range(-5, 5))

True

Immutable constraints and frozen sets

Sets are powerful and flexible objects, but they do have one constraint in both 3.0 and 2.6 that you should keep in mind—largely because of their implementation, sets can only contain immutable (a.k.a “hashable”) object types. Hence, lists and dictionaries cannot be embedded in sets, but tuples can if you need to store compound values. Tuples compare by their full values when used in set operations:

>>> S

{1.23}

>>> S.add([1, 2, 3]) # Only immutable objects work in a set

TypeError: unhashable type: 'list'

>>> S.add({'a':1})

TypeError: unhashable type: 'dict'

>>> S.add((1, 2, 3))

>>> S # No list or dict, but tuple okay

{1.23, (1, 2, 3)}

>>> S | {(4, 5, 6), (1, 2, 3)} # Union: same as S.union(...)

{1.23, (4, 5, 6), (1, 2, 3)}

>>> (1, 2, 3) in S # Membership: by complete values

True

>>> (1, 4, 3) in S

False

Tuples in a set, for instance, might be used to represent dates, records, IP addresses, and so on (more on tuples later in this part of the book). Sets themselves are mutable too, and so cannot be nested in other sets directly; if you need to store a set inside another set, the frozenset built-in call works just like set but creates an immutable set that cannot change and thus can be embedded in other sets.

Set comprehensions in Python 3.0

In addition to literals, 3.0 introduces a set comprehension construct; it is similar in form to the list comprehension

Return Main Page Previous Page Next Page

®Online Book Reader