add vs update in set operations in python

前端 未结 9 601
天涯浪人
天涯浪人 2020-12-07 18:30

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) #         


        
相关标签:
9条回答
  • 2020-12-07 19:06

    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])
    
    0 讨论(0)
  • 2020-12-07 19:07

    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.

    0 讨论(0)
  • 2020-12-07 19:11

    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 讨论(0)
提交回复
热议问题