6.3 Sets
A set is an unordered collection of unique values. Sets may contain only immutable objects, like strings, int
s, float
s and tuples that contain only immutable elements. Though sets are iterable, they are not sequences and do not support indexing and slicing with square brackets, []
. Dictionaries also do not support slicing.
Creating a Set with Curly Braces
The following code creates a set of strings named colors
:
In [1]: colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'}
In [2]: colors
Out[2]: {'blue', 'green', 'orange', 'red', 'yellow'}
Notice that the duplicate string 'red'
was ignored (without causing an error). An important use of sets is duplicate elimination, which is automatic when creating a set. Also, the resulting ...
Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.