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) #
add
adds an element, update
"adds" another iterable set
, list
or tuple
, for example:
In [2]: my_set = {1,2,3}
In [3]: my_set.add(5)
In [4]: my_set
Out[4]: set([1, 2, 3, 5])
In [5]: my_set.update({6,7})
In [6]: my_set
Out[6]: set([1, 2, 3, 5, 6, 7])
a.update(1)
in your code won't work. add
accepts an element and put it in the set if it is not already there but update
takes an iterable and makes a unions of the set with that iterable. It's kind of like append
and extend
for the lists.
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.