-2

I am a newbie to programming, while I was learning about sets in Python I encountered this problem. when I pass a tuple as argument to add method, the tuple is included in set_1, whereas when I pass a list as argument to add method is causes a TypeError: unhashable type: 'list' in the code given below.

set_1 = {"a", "b", "c"}

set_1.add((1,2,3))
print(set_1)

set_1.add([4,5,6])
print(set_1)

Kindly, state the reason for this error and explain why hashing takes place while passing a list as argument into set.add() method

Aswin
  • 1
  • 1
  • 1
    Does this answer your question? [How does hashing work for python sets](https://stackoverflow.com/questions/38123760/how-does-hashing-work-for-python-sets) – Ignatius Reilly May 28 '23 at 03:15
  • 1
    [In Python, why is a tuple hashable but not a list?](https://stackoverflow.com/questions/42203673) and [What makes lists unhashable?](https://stackoverflow.com/questions/23268899). – Ignatius Reilly May 28 '23 at 03:17
  • The point of hashing is that a given object will always have **the same hash**. But lists are mutable, so it makes no sense to hash a list. I mean, you **could**, but the hash would change whenever the list contents changed, which defeats the point. – John Gordon May 28 '23 at 03:21

2 Answers2

0

To be added to a set, the object must be immutable. Tuples, strings, and numbers all meet this requirement and thus can be added to a set. Lists, on the other hand, are mutable and, thus, can't be added.

sizzzzlerz
  • 4,277
  • 3
  • 27
  • 35
0

The key thing is to understand the differences between immutable and mutable. One type of object is changeable at run-time while the other is set and cannot be modified. List in this case is mutable.

A tuple or set is immutable the values cannot change so the hash cannot change either. List on the other hand is mutable one can later add, remove, delete elements that would be going against what hash does.

de_classified
  • 1,927
  • 1
  • 15
  • 19