3.4. Sequence Frozenset

3.4.1. Rationale

  • Only unique values

  • Immutable - cannot add, modify or remove items

  • Can store elements of any hashable types

  • Has all set methods such as .intersect(), .subset() .union(), etc.

  • One solid block in memory

3.4.2. Type Definition

  • Set is ordered data structure

  • Do not support getitem

  • Do not support slice

  • Defining only with frozenset() - no short syntax

  • Comma after last element is optional

  • Brackets are required

Listing 3.9. set type definition
data = frozenset()

data = frozenset({1})
data = frozenset({1, 2, 3})
data = frozenset({1.1, 2.2, 3.3})
data = frozenset({True, False})
data = frozenset({'a', 'b', 'c'})
data = frozenset({'a', 1, 2.2, True, None})

3.4.3. Type Casting

  • frozenset() converts argument to frozenset

data = [1, 2, 3]
frozenset(data)
# frozenset({1, 2, 3})
data = (1, 2, 3)
frozenset(data)
# frozenset({1, 2, 3})
data = {1, 2, 3}
frozenset(data)
# frozenset({1, 2, 3})
data = frozenset({1, 2, 3})
frozenset(data)
# frozenset({1, 2, 3})
data = [1, 2, 3, [4, 5]]
frozenset(data)
# TypeError: unhashable type: 'list'
data = [1, 2, 3, (4, 5)]
frozenset(data)
# frozenset({(4, 5), 1, 2, 3})

3.4.4. Frozenset or Set

Both:

  • unique elements

  • only hashable elements

Frozenset:

  • ordered

  • immutable

  • one contingent block of data in memory

Set:

  • unordered

  • mutable

  • implemented in memory as list of pointers to objects

  • objects are scattered in memory

3.4.5. Assignments

3.4.5.1. Sequence Frozenset Newline

English
  1. Use data from "Input" section (see below)

  2. Define result: str

  3. Use str.join() to join lines of text with newline (\n) character

  4. Compare result with "Output" section (see below)

Polish
  1. Użyj danych z sekcji "Input" (patrz poniżej)

  2. Zdefiniuj result: str

  3. Użyj str.join() aby połączyć linie tekstu znakiem końca linii (\n)

  4. Porównaj wyniki z sekcją "Output" (patrz poniżej)

Innput
DATA = frozenset({
    'We choose to go to the Moon.',
    'We choose to go to the Moon in this decade and do the other things.',
    'Not because they are easy, but because they are hard.'})
Output
result: str
# 'We choose to go to the Moon.\nWe choose to go to the Moon in this decade and do the other things.\nNot because they are easy, but because they are hard.'