3. set

  • Only unique values

  • Mutable - can add, remove, and modify items

3.1. Initializing

  • Do not record element position

  • Do not record order of insertion

  • Do not support indexing

  • Do not support slicing

3.1.1. Initialize empty

  • Defining only with set()

my_set = set()

3.1.2. Initialize with one element

  • Comma after last element is optional

  • Brackets are required

my_set = {1}
my_set = {1,}

3.1.3. Initialize with many elements

  • Brackets are required

  • Only unique values

  • Can store elements of any hashable types

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

3.2. Adding items

3.2.1. Adding one element

my_set = {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}

3.2.2. Adding many items

my_set = {1, 2, 3}

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

3.3. Removing items

my_set = {1, 2, 3}

value = my_set.pop()

my_set  # {1, 2}
value   # 3

3.4. Converting to set deduplicate items

3.4.1. Converting list to set

Listing 2. Converting list to set deduplicate items
names = [
    'Twardowski',
    'Иванович',
    'Jiménez',
    'Twardowski'
]

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

3.4.2. Converting tuple to set

Listing 3. Converting tuple to set deduplicate items
names = (
    'Twardowski',
    'Иванович',
    'Jiménez',
    'Twardowski'
)

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

3.5. Length of a set

my_set = {1, 2, 3}

len(my_set)
# 3

3.6. Assignments

3.6.1. Create

  • Complexity level: easy

  • Lines of code to write: 13 lines

  • Estimated time of completion: 5 min

  • Filename: solution/set_create.py

Table 16. Pomiary Iris

Sepal length

Sepal width

Petal length

Petal width

Species

5.8

2.7

5.1

1.9

virginica

5.1

3.5

1.4

0.2

setosa

5.7

2.8

4.1

1.3

versicolor

6.3

2.9

5.6

1.8

virginica

6.4

3.2

4.5

1.5

versicolor

  1. Dane są pomiary Table 16.

  2. Stwórz set na podstawie pierwszego wiersza

  3. Wartości z dwóch kolejnych wierszy dodawaj do zbioru za pomocą .add()

  4. Przedostatni wiersz dodaj za pomocą .update() jako tuple

  5. Ostatni wiersz dodaj za pomocą .update() jako list