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.
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.
set.add
set.add
adds an individual element to the set. So,works, but it cannot work with an iterable, unless it is hashable. That is the reason why
a.add([1, 2])
fails.Here,
[1, 2]
is treated as the element being added to the set and as the error message says, a list cannot be hashed but all the elements of a set are expected to be hashables. Quoting the documentation,set.update
In case of
set.update
, you can pass multiple iterables to it and it will iterate all iterables and will include the individual elements in the set. Remember: It can accept only iterables. That is why you are getting an error when you try to update it with1
But, the following would work because the list
[1]
is iterated and the elements of the list are added to the set.set.update
is basically an equivalent of in-place set union operation. Consider the following casesHere, we explicitly convert all the iterables to sets and then we find the union. There are multiple intermediate sets and unions. In this case,
set.update
serves as a good helper function. Since it accepts any iterable, you can simply doadd
is faster for a single element because it is exactly for that purpose, adding a single element:update
expects an iterable or iterables so if you have a single hashable element to add then useadd
if you have an iterable or iterables of hashable elements to add useupdate
..add()
is intended for a singleelement
, while.update()
is for the introduction of other sets.From help():
add
adds an element,update
"adds" another iterableset
,list
ortuple
, for example: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 butupdate
takes an iterable and makes a unions of the set with that iterable. It's kind of likeappend
andextend
for the lists.I guess no one mentioned about the good resource from Hackerrank. I'd like to paste how Hackerrank mentions the difference between update and add for set in python.
Sets are unordered bag of unique values. A single set contains values of any immutable data type.
CREATING SET
MODIFYING SET - add() and update()
Hope it helps. For more details on Hackerrank, here is the link.