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?
2 Answers 2
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.
3 Comments
{1 2 3} and {3 2 1} are the same set.O(log n) according to C++ standard, programmers do. Math doesn't care that the worst case for the find operation on a set in Python is O(n) (being O(1) in ordinary circumstances), programmers do.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.