Python Add Set Item

In Python, you can add elements to a set using the add() and update() methods.

Adding a Single Element with add()

The add() method adds a single element to the set. If the element is already in the set, it won’t be added again, as sets only contain unique items.


data_set = {1, 2, 3, 4, 5}
data_set.add(6)  # Adds 6 to the set
print(data_set)  # Output: {1, 2, 3, 4, 5, 6}

data_set.add(2)  # Adding a duplicate value; nothing changes
print(data_set)  # Output: {1, 2, 3, 4, 5, 6}

Example2:


# Initialize a set
fruits = {"apple", "banana"}

# Add a single element
fruits.add("orange")
print(fruits)  # Output: {"apple", "banana", "orange"}

Adding Multiple Elements with update()

To add multiple elements at once, use the update() method. You can pass any iterable (like a list, tuple, or another set), and all unique items from that iterable will be added to the set.


data_set = {1, 2, 3, 4, 5}
data_set.update([6, 7, 8])  # Adds 6, 7, and 8 to the set
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8}

# Adding elements from another set
data_set.update({7, 8, 9})
print(data_set)  # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}

# Adding elements from a string (unique characters will be added)
my_set.update("hello")
print(data_set)  # Output may include {1, 2, 3, 4, 5, 6, 7, 8, 9, 'h', 'e', 'l', 'o'}

Example2:


# Initialize a set
fruits = {"apple", "banana"}

# Add multiple elements
fruits.update(["mango", "orange"])
print(fruits)  # Output: {"apple", "banana", "mango", "orange"}

Python Add Set Item – Interview Questions

Q 1: How do you add a single item to a set?
Ans: Using the add() method.
Q 2: How do you add multiple items to a set?
Ans: Using the update() method with a list or another set.
Q 3: Can adding a duplicate item affect the set?
Ans: No, duplicates are ignored automatically.
Q 4: Can a set contain mutable elements?
Ans: No, elements must be immutable types.
Q 5: Does add() return a value?
Ans: No, it updates the set in place.

Python Add Set Item – Objective Questions (MCQs)

Q1. Which method is used to add a single element to a set?






Q2. What will be the output of the following code?

s = {10, 20}
s.add(30)
print(s)






Q3. Which method can be used to add multiple elements to a set at once?






Q4. What will be the output of this code?

s = {1, 2}
s.update([3, 4])
print(s)






Q5. What happens when you try to add a duplicate element to a set?






Related Python Add Set Item Topics