93

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.

aceminer
  • 4,089
  • 9
  • 56
  • 104

9 Answers9

113

set.add

set.add adds an individual element to the set. So,

>>> a = set()
>>> a.add(1)
>>> a
set([1])

works, but it cannot work with an iterable, unless it is hashable. That is the reason why a.add([1, 2]) fails.

>>> a.add([1, 2])
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'

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,

Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable.

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 with 1

>>> a.update(1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable

But, the following would work because the list [1] is iterated and the elements of the list are added to the set.

>>> a.update([1])
>>> a
set([1])

set.update is basically an equivalent of in-place set union operation. Consider the following cases

>>> set([1, 2]) | set([3, 4]) | set([1, 3])
set([1, 2, 3, 4])
>>> set([1, 2]) | set(range(3, 5)) | set(i for i in range(1, 5) if i % 2 == 1)
set([1, 2, 3, 4])

Here, 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 do

>>> a.update([1, 2], range(3, 5), (i for i in range(1, 5) if i % 2 == 1))
>>> a
set([1, 2, 3, 4])
Matt
  • 27,170
  • 6
  • 80
  • 74
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • In case you want to update my_set from the sets in an iterable of iterables you must use `my_set.update(*[s for s in iterable])`, passing a generator in as in `my_set.update(s for s in iterable)` will update the set with the elements of the iterable and will blow if those elements are not hashable – Mr_and_Mrs_D Jun 09 '17 at 20:51
27

add is faster for a single element because it is exactly for that purpose, adding a single element:

In [5]: timeit a.update([1])
10000000 loops, best of 3: 191 ns per loop

In [6]: timeit a.add(1) 
10000000 loops, best of 3: 69.9 ns per loop

update expects an iterable or iterables so if you have a single hashable element to add then use add if you have an iterable or iterables of hashable elements to add use update.

s.add(x) add element x to set s

s.update(t) s |= t return set s with elements added from t

Community
  • 1
  • 1
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 6
    While this is probably obvious, it should be noted that `update` is much faster for adding lots of elements at once: `timeit a.update( range(10000) ) # => 1000 loops, best of 3: 431 µs per loop`, meanwhile `timeit for i in range(10000): a.add(i) # => 1000 loops, best of 3: 1.18 ms per loop` – Matt Hancock Mar 14 '16 at 18:34
12

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])
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • Just a note that this notation is fairly recent. Python 2.7 and Python 3.1, according to http://stackoverflow.com/a/31072911/1143274 – Evgeni Sergeev Aug 02 '15 at 12:03
5

.add() is intended for a single element, while .update() is for the introduction of other sets.

From help():

add(...)
    Add an element to a set.

    This has no effect if the element is already present.


update(...)
    Update a set with the union of itself and others.
monkut
  • 42,176
  • 24
  • 124
  • 155
3

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

Jamerson
  • 474
  • 3
  • 14
3

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.

ekipmanager
  • 116
  • 4
1

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

myset = {1, 2} # Directly assigning values to a set

myset = set() # Initializing a set

myset = set(['a', 'b']) # Creating a set from a list

print(myset)  ===> {'a', 'b'}

MODIFYING SET - add() and update()

myset.add('c')

myset  ===>{'a', 'c', 'b'}

myset.add('a') # As 'a' already exists in the set, nothing happens

myset.add((5, 4))

print(myset) ===> {'a', 'c', 'b', (5, 4)} 


myset.update([1, 2, 3, 4]) # update() only works for iterable objects

print(myset) ===> {'a', 1, 'c', 'b', 4, 2, (5, 4), 3}

myset.update({1, 7, 8})

print(myset) ===>{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}

myset.update({1, 6}, [5, 13])

print(myset) ===> {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}

Hope it helps. For more details on Hackerrank, here is the link.

Micho
  • 3,929
  • 13
  • 37
  • 40
harrisonthu
  • 454
  • 3
  • 7
  • 18
0

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.

0

We use add() method to add single value to a set.

We use update() method to add sequence values to a set.

Here Sequences are any iterables including list,tuple,string,dict etc.

mousetail
  • 7,009
  • 4
  • 25
  • 45
Rudra
  • 1