Phoenix
Phoenix

Reputation: 4656

Understanding set()

Reading the python docs I come to set(). At the moment my understanding is considering that set is a term used to define instances of frozenset, list, tuple, and dict classes.

Firstly, is this correct?

Secondly, could anyone supply further information that may expose set()'s place in python?

Upvotes: 0

Views: 113

Answers (2)

C.B.
C.B.

Reputation: 8346

In addition to matt b's answer, from the doc --

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Upvotes: 3

matt b
matt b

Reputation: 140061

A Python set is the same concept as a mathematical set.

Sets contain only unique elements and are an unordered collection, there is no such thing as the "first" or "second" element in a set.

>>> a = set()
>>> a.add(1)
>>> a
set([1])
>>> a.add(1)
>>> a
set([1])

You cannot index a set:

>>> a[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing

Sets can be iterated, but the order of iteration is not defined and should never be relied upon:

>>> for x in {1, 3, 2}:
...     print x
...
1
2
3

dict and list are not sets, you might be confused by the fact that the set documentation appears in the same area of the Python docs as the other collections; while a frozenset is a particular type of set.

Upvotes: 5

Related Questions