Python-Ref > Data structures > Sets > Set limits and frozen sets
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Set limits and frozen sets

What a list cannot store and how to fix it.
Because a set is hash-based to provide fast lookup, it cannot store mutable types, such as lists or other sets.
Expand/Shrink
Zdroj: (sets7-1.py)
  1   set1 = set()
  2   set1.add( [1,2,3])
stderr:
Traceback (most recent call last):
  File "sets7-1.py", line 2, in <module>
    set1.add( [1,2,3])
TypeError: list objects are unhashable
Doba běhu: 21.1 ms
Expand/Shrink
Zdroj: (sets7-2.py)
  1   set1 = set()
  2   set2 = set( [1,2,3])
  3   set1.add( set2)
stderr:
Traceback (most recent call last):
  File "sets7-2.py", line 3, in <module>
    set1.add( set2)
TypeError: set objects are unhashable
Doba běhu: 18.6 ms
This limitation is similar to the limitation imposed on dictionary keys.
To overcome this limitation when using list, we can use tuples which are a immutable counterpart of lists. In case of sets we have a similar type avialable - the frozen set. It is an immutable version of set which can be used both in dictionary keys and in sets.
Expand/Shrink
Zdroj: (sets7-3.py)
  1   set1 = set()
  2   set2 = frozenset( [1,2,3])
  3   set1.add( set2)
  4   print set1
  5   
  6   set1.add( tuple( [1,2,3]))
  7   print set1
stdout:
set([frozenset([1, 2, 3])])
set([frozenset([1, 2, 3]), (1, 2, 3)])
Doba běhu: 18.7 ms