avatarLiu Zuo Lin

Summarize

Frozensets VS Normal Sets in Python in 30 Seconds

# If you read fast

Newsflash — Python has a built-in frozenset type which we do not need to import. This is kinda similar to our usual set type, but with a couple of main differences.

1) How we create frozensets vs sets

# creating a set

a = set([1, 2, 3])

# or

a = {1, 2, 3}
# creating a frozenset
b = frozenset([1, 2, 3])

Note — this is built-in and we do not need to import anything

2) Frozensets are immutable; Sets are mutable

a = {1, 2, 3}
a.add(4)
print(a)    # {1, 2, 3, 4}

a.remove(1)
print(a)    # {2, 3, 4}

^ sets are mutable. We can add/remove stuff into our set after we create it.

b = frozenset([1, 2, 3])
b.add(4)      # ERROR
b.remove(4)   # ERROR

^ frozensets are immutable. We cannot add/remove stuff from our frozenset after we create it.

3) Frozenset advantage 1

We CAN add a frozenset into another set

We CANNOT add a normal set into another set

Frozensets being immutable means that we cannot add/remove stuff to/from it after we’ve created our frozenset. It does however mean that we can add a frozenset into a set.

fs = frozenset([1, 2, 3])

s = set()
s.add(fs)    # no problem

Sets being mutable also means that we cannot add a set to another set.

x = set([1, 2, 3])

s = set()
s.add(x)      # TypeError: unhashable type: 'set'

4) Frozenset advantage 2

We CAN use a frozenset as a dictionary key

We CANNOT use a normal set as a dictionary key

Same concept as above — frozensets are immutable, hence hashable, and hence we can use it as a dictionary key.

d = {
  frozenset([1,2,3]): 'hello',
  frozenset([1,2,3,4]): 'world',
}

# no problem

Normal sets are mutable, hence unhashable, and hence we cannot use a normal set as a dictionary key.

d = {
  set([1, 2, 3]): 'apple'
}

# TypeError: unhashable type: 'set'

So when should we use frozensets over sets?

When we want to take advantage of its immutability, and ability to be hashed — which allows us to 1) add a frozenset to another set 2) use a frozenset as a dictionary key (and other more obscure use cases)

Conclusion

I hope this was helpful in some way

If You Wish To Support Me As A Creator

  1. Clap 50 times for this story
  2. Leave a comment telling me your thoughts
  3. Highlight your favourite part of the story

Thank you! These tiny actions go a long way, and I really appreciate it!

YouTube: https://www.youtube.com/@zlliu246

LinkedIn: https://www.linkedin.com/in/zlliu/

My Ebooks: https://zlliu.co/ebooks

Python
Programming
Python Programming
Coding
Python3
Recommended from ReadMedium