add vs update in set operations in python

前端 未结 9 602
天涯浪人
天涯浪人 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 18:58

    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.

提交回复
热议问题