What sets are and arent

Here's how sets fit in with the rest of Python's data types:

• The set() type is built into Python 2.4 and later. If you're using Python 2.3, you must import the sets module before using sets. The data type in the sets module is called Set() (with a capital S), not set().

• Like a dict, a set is an unordered collection of elements.

• Unlike a dict, a set contains only keys (that is, unique, immutable objects). A set does not have values, and it is not a mapping type.

• Unlike a sequence, the elements in sets aren't stored in any particular order, so sets don't support indexing or slicing.

• In sequences, an element can occur multiple times, but a set contains only unique elements, no duplicates.

• Regular sets are mutable, and you can't use one as an element of another set or as a dictionary key. (But see the section, "Immutable or frozen sets," later in this chapter.)

Here's an example of a set based on a list that contains some duplicate elements. The set contains no duplicates.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruits = set(basket) >>> fruits set(['orange', 'pear', 'apple', 'banana'])

Was this article helpful?

0 0

Post a comment