Python: Add member in a set
3. Add Member(s) to a Set
Write a Python program to add member(s) to a set.
Visual Presentation:
Sample Solution:
Python Code:
# Create a new empty set 'color_set':
color_set = set()
# Print the empty set 'color_set':
print(color_set)
# Print a newline for separation:
print("\nAdd single element:")
# Add a single element "Red" to the 'color_set':
color_set.add("Red")
# Print the 'color_set' with the added element "Red":
print(color_set)
# Print a newline for separation:
print("\nAdd multiple items:")
# Add multiple elements "Blue" and "Green" to the 'color_set' using the 'update' method:
color_set.update(["Blue", "Green"])
# Print the 'color_set' with the added elements "Blue" and "Green":
print(color_set)
Sample Output:
set() Add single element: {'Red'} Add multiple items: {'Green', 'Red', 'Blue'}
For more Practice: Solve these Related Problems:
- Write a Python program to add multiple elements to a set using the update() method and print the new set.
- Write a Python program to take a list of values and add them to an existing set, ensuring no duplicates are introduced.
- Write a Python program to implement a function that accepts a set and a variable number of arguments, adding each to the set.
- Write a Python program to dynamically add elements to a set based on user input until a specific stop word is entered.
Python Code Editor:
Previous: Write a Python program to iteration over sets.
Next: Write a Python program to remove item(s) from a given set.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics