Introduction to the difference between add and update in python set set

  • 2021-09-20 21:11:46
  • OfStack

The set set is a set of unordered non-repeating elements


set(['hello','hello','hi'])
# {'hello', 'hi'}
set('hello hello hi')
# {' ', 'e', 'h', 'i', 'l', 'o'}

Differences between set. add () and set. update ()


myset1 = set()
myset1.add('hello')
#{'hello'}
myset1.update('world')
#{'d', 'hello', 'l', 'o', 'r', 'w'}
myset2 = set()
myset2.add('123')
myset2.update('123')
#{'1', '123', '2', '3'}

Supplement: Add vs update to set operation in python

If I only want to add a single value to the collection, what's the difference between adding and updating operations in python.


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

Someone can explain why this is the case.

Solution


set.add

set. add adds a single element to the collection. So,


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

It works, but it cannot be used with iterable1 unless it is cleanable. This is why a. add ([1, 2]) failed.


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

Here, [1, 2] is considered to be an element added to the collection, and as the error message indicates, a list cannot be hashed but all elements of the collection should be hashables. Referring to documentation,

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

set.update

In the case of set. update, you can pass it multiple iterations, which will iterate over all iterations and will include the individual elements in the collection. Remember: It only accepts iterations. That's why you get 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

However, the following approach works because the list [1] is iterated and the elements of the list are added to the collection.


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

set. update is basically equivalent to assembling and operating in place. Consider the following


>>> 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 iterations to sets, and then we find union. There are multiple intermediate sets and unions. In this case, set. update can be a good helper function. Since it accepts anything that can be iterated, you can do it


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

Related articles: