6.3 Sets

  • A set is an unordered collection of unique values.
  • May contain only immutable objects, like strings, ints, floats and tuples that contain only immutable elements.
  • Sets do not support indexing and slicing.

Creating a Set with Curly Braces

  • Duplicates are ignored, making sets great for duplicate elimination.
In [1]:
colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'}
  • Though the output below is sorted, sets are unordered—do not write order-dependent code.
In [2]:
colors
Out[2]:
{'blue', 'green', 'orange', 'red', 'yellow'}

Determining a Set’s Length

In [3]:
len(colors)
Out[3]:
5

Checking Whether a Value Is in a Set

In [4]:
'red' in colors
Out[4]:
True
In [5]:
'purple' in colors
Out[5]:
False
In [6]:
'purple' not in colors
Out[6]:
True

Iterating Through a Set

  • There’s no significance to the iteration order.
In [7]:
for color in colors:
    print(color.upper(), end=' ')
    
YELLOW BLUE GREEN RED ORANGE 

Creating a Set with the Built-In set Function

In [8]:
numbers = list(range(10)) + list(range(5))
In [9]:
numbers
Out[9]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
In [10]:
set(numbers)
Out[10]:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  • To create an empty set, must use the set(), because {} represents an empty dictionary.
  • Python displays an empty set as set() to avoid confusion with an empty dictionary ({}).
In [11]:
set()
Out[11]:
set()

Frozenset: An Immutable Set Type

  • Sets are mutable.
  • Set elements must be immutable; therefore, a set cannot have other sets as elements.
  • A frozenset is an immutable set—it cannot be modified after you create it, so a set can contain frozensets as elements.
  • The built-in function frozenset creates a frozenset from any iterable.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 6 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.