7. set

  • Can store elements of any hashable types
  • Only unique values
  • Mutable - can add, remove, and modify items
  • Brackets are required
  • Comma after last element is optional

7.1. Defining set

  • Defining only with set()

7.1.1. Empty set

my_set = set()

7.1.2. set with one element

my_set = {1}
my_set = {1,}

7.1.3. set with multiple values

my_set = {1, 3, 1}          # {1, 3}

7.1.4. set with multiple values in many types

my_set = {1, 2.0, 'Jose'}   # {1, 2.0, 'Jose'}
my_set = {1, 2.0, (3, 4)}   # {1, 2.0, (3, 4)}
my_set = {1, 2.0, [3, 4]}   # TypeError: unhashable type: 'list'
my_set = {1, 2.0, {3, 4}}   # TypeError: unhashable type: 'set'

7.2. Adding items

7.2.1. Adding one element

my_set = {1, 2, 3}          # {1, 2, 3}

my_set.add(4)               # {1, 2, 3, 4}
my_set.add(4)               # {1, 2, 3, 4}
my_set.add(3)               # {1, 2, 3, 4}

7.2.2. Adding many items

my_set = {1, 2, 3}          # {1, 2, 3}

my_set.update([4, 5])       # {1, 2, 3, 4, 5}

7.3. set arithmetics

{1,2} - {2,3}    # {1}        # Subtract
{1,2} | {2,3}    # {1, 2, 3}  # Sum
{1,2} & {2,3}    # {2}        # Union
{1,2} ^ {2,3}    # {1, 3}     # Symmetrical difference
{1,2} + {3,4}    # TypeError: unsupported operand type(s) for +: 'set' and 'set'

7.4. Slicing set

  • Slicing set is not possible
  • More in Slicing chapter
my_set = {1, 2.0, None, False, 'José'}

my_set[1]                   # TypeError: 'set' object does not support indexing
my_set[2:4]                 # TypeError: 'set' object does not support indexing

7.5. Length of a set

my_set = {1, 2, 3}

len(my_set)                 # 3

7.6. Converting list to set deduplicate items

names = ['Twardowski', 'Иван', 'Jiménez', 'Twardowski']

unique_names = set(names)
# {'Twardowski', 'Иван', 'Jiménez'}