Set immutabili in Python con frozenset
frozenset è una funzione di Python che crea dei set immutabili.
In Python i set sono liste di dati non ordinato che non accettano duplicati.
Ma è sempre possibile aggiungere o rimuovere elementi.
Ad esempio:
my_set = {'a', 'b', 'c'}
print(my_set)
my_set.add('d')
print(my_set)
frozenset accetta un prarametro, un iterable, dal quale crea appunto un set immutabile.
Tanto per fare un esempio:
my_set = {'a', 'b', 'c'}
print(my_set)
my_set.add('d')
print(my_set)
frozen_set = frozenset(my_set)
print(frozen_set)
frozen_set.add('e')
print(frozen_set)
Il risultato sarà questo:
{'c', 'a', 'b'}
{'d', 'c', 'a', 'b'}
frozenset({'d', 'c', 'a', 'b'})
Traceback (most recent call last):
File "/home/fermat/TEST/test-python/main.py", line 8, in
frozen_set.add('e')
^^^^^^^^^^^^^^
AttributeError: 'frozenset' object has no attribute 'add'
E' possibile passargli anche altri oggetti iterable, tipo un dictionary; in questo caso creerà il set immutabile con le chiavi.
Ad esempio:
my_disct = {"titolo": "IT", "autore": "Stephen King", "prezzo": 20}
print(my_disct)
frozen_set = frozenset(my_disct)
print(frozen_set)
Enjoy!
python frozenset
Commentami!