How to Add Items to a Python Set

Discover how to add new items to a Python set. Although you cannot modify existing items in a set, you can easily add new ones using the add() method. Check out the example to see how it's done.



Python - Add Set Items

Add Items

Once a set is created, you cannot change its items, but you can add new items.

Example

  thisset = {"orange", "grape", "mango"}
  
  thisset.add("apple")
  
  print(thisset)
              
Output

  {'orange', 'grape', 'mango', 'apple'}
              

Example

Add elements from another set into the current set using the update() method:

Example

  thisset = {"orange", "grape", "mango"}
  tropical = {"pineapple", "coconut", "papaya"}
  
  thisset.update(tropical)
  
  print(thisset)
              
Output

  {'orange', 'grape', 'mango', 'papaya', 'pineapple', 'coconut'}
              

Example

Add elements of a list to a set using the update() method:

Example

  thisset = {"orange", "grape", "mango"}
  mylist = ["kiwi", "banana"]
  
  thisset.update(mylist)
  
  print(thisset)
              
Output

  {'orange', 'grape', 'mango', 'banana', 'kiwi'}