2. set

  • Only unique values

  • Can store elements of any hashable types

  • Mutable - can add, remove, and modify items

  • Brackets are required

  • Comma after last element is optional

2.1. Defining set

  • Defining only with set()

  • Is an unordered collection

  • set do not record element position or order of insertion

  • set do not support indexing, slicing, or other sequence-like behavior

2.1.1. Empty set

my_set = set()

2.1.2. set with one element

my_set = {1}
my_set = {1,}

2.1.3. set with multiple values

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

2.1.4. set with multiple values in many types

my_set = {1, 2.0, 'Jan'}    # {1, 2.0, 'Jan'}
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'

2.2. Adding items

2.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}

2.2.2. Adding many items

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

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

2.3. Length of a set

my_set = {1, 2, 3}

len(my_set)                 # 3

2.4. Converting list to set deduplicate items

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

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