add vs update in set operations in python

2019-01-16 12:19发布

What is the difference between add and update operations in python if i just want to add a single value to the set.

a = set()
a.update([1]) #works
a.add(1) #works
a.update([1,2])#works
a.add([1,2])#fails 

Can someone explain why is this so.

标签: python set
8条回答
Animai°情兽
2楼-- · 2019-01-16 12:55

add method directly adds elements to the set while the update method converts first argument into set then it adds the list is hashable therefore we cannot add a hashable list to unhashable set.

查看更多
狗以群分
3楼-- · 2019-01-16 12:59

add only accepts a hashable type. A list is not hashable.

查看更多
登录 后发表回答