Table of Contents
ToggleAdding set items implies including new elements into an existing set. This guide explains different methods like add(), update(), union, and set comprehension to modify and expand sets efficiently.
The add() method in Python is used to add a single element to a set. If the element is already in the set, it remains unchanged.
# Defining an empty set
language = set()
# Adding elements to the set using add() method
language.add("C")
language.add("C++")
language.add("Java")
language.add("Python")
# Printing the updated set
print("Updated Set:", language)
Output: {‘Python’, ‘Java’, ‘C++’, ‘C’}
The update() method allows adding multiple elements from an iterable to a set.
# Define a set
my_set = {1, 2, 3}
# Adding element to the set
my_set.update([4])
print("Updated Set:", my_set)
Output: {1, 2, 3, 4}
The union() method and | operator combine sets, ensuring all unique elements are included.
# Defining sets
lang1 = {"C", "C++", "Java", "Python"}
lang2 = {"PHP", "C#", "Perl"}
lang3 = {"SQL", "C#"}
# Performing union operation
combined_set1 = lang1.union(lang2)
combined_set2 = lang2 | lang3
print("Combined Set1:", combined_set1)
print("Combined Set2:", combined_set2)
Output:
Combined Set1: {‘C#’, ‘Perl’, ‘C++’, ‘Java’, ‘PHP’, ‘Python’, ‘C’}
Combined Set2: {‘C#’, ‘Perl’, ‘PHP’, ‘SQL’}
Set comprehension is a concise way to create sets based on an existing iterable.
# Defining a list
numbers = [1, 2, 3, 4, 5]
# Creating a set with squares of numbers
squares_set = {num ** 2 for num in numbers}
print("Squares Set:", squares_set)
Output: Squares Set: {1, 4, 9, 16, 25}
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now