Introduction
Union and intersection help you find common or combined items from two groups. They make comparing lists or sets easy.
Jump into concepts and practice - no test required
Union and intersection help you find common or combined items from two groups. They make comparing lists or sets easy.
set1.union(set2) set1.intersection(set2)
union() returns all unique items from both sets.
intersection() returns only items found in both sets.
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b))a = {1, 2, 3}
b = {3, 4, 5}
print(a.intersection(b))This program finds all unique friends from two groups and also finds friends they both have.
friends_a = {"Alice", "Bob", "Charlie"}
friends_b = {"Bob", "Diana", "Eve"}
all_friends = friends_a.union(friends_b)
common_friends = friends_a.intersection(friends_b)
print("All friends:", all_friends)
print("Common friends:", common_friends)Sets automatically remove duplicates, so union never repeats items.
Order of items in sets when printed may vary because sets are unordered.
Union combines all unique items from two sets.
Intersection finds only items common to both sets.
Use these to compare or merge groups easily.
union operation do when applied to two sets in Python?a and b in Python?& operator or the .intersection() method.| is union, + is invalid for sets, - is difference.set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.intersection(set2))set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 + set2)+ operator; this causes a TypeError.| operator or .union() method to combine sets.list1 = ['Anna', 'Bob', 'Cara'] and list2 = ['Bob', 'Diana', 'Anna'], which Python code correctly finds students present in both lists using set operations?set(list1) & set(list2) returns elements in both sets.