O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sets

A set is used to contain an unordered collection of objects. To create a set, use the set() function and supply a sequence of items such as follows:

s = set([3,5,9,10])       # Create a set of numbers
t = set("Hello")          # Create a set of characters

Unlike lists and tuples, sets are unordered and cannot be indexed in the same way. More over, the elements of a set are never duplicated. For example, if you print the value of t from the preceding code, you get the following:

>>> print t
set(['H', 'e', 'l', 'o'])

Notice that only one 'l' appears.

Sets support a standard collection of set operations, including union, intersection, difference, and symmetric difference. For example:

 a = t | s # Union of t and s b = t & s # Intersection of t and s c ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required