Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
78 views
in Python by (114k points)
How to perform set operations in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (114k points)

Python provides several set operations that you can use to perform different operations on sets. Here are some of the most commonly used set operations:

Union (| or union()): The union of two or more sets is a new set that contains all the unique elements from all the sets.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
union_set = set1.union(set2, set3)
print(union_set)  # Output: {1, 2, 3, 4, 5}
 

Intersection (& or intersection()): The intersection of two or more sets is a new set that contains only the common elements present in all the sets.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5}
intersection_set = set1.intersection(set2, set3)
print(intersection_set)  # Output: {3}
 

Difference (- or difference()): The difference between two sets is a new set that contains only the elements present in the first set but not in the second set.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference_set = set1.difference(set2)
print(difference_set)  # Output: {1}
 

Symmetric Difference (^ or symmetric_difference()): The symmetric difference between two sets is a new set that contains only the elements that are present in either of the sets, but not in both.

Example:

set1 = {1, 2, 3}
set2 = {2, 3, 4}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)  # Output: {1, 4}
 

Note that all these operations return a new set and do not modify the original sets.

Related questions

0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer
asked Mar 22, 2023 in Python by kvdevika (114k points)
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...