Set Exercises
Test your understanding of Python sets with these exercises:
Exercise 1: Create a Set
Create a set of your three favorite sports and print it.
Python
# Your code here
sports = {"soccer", "basketball", "tennis"}
print(sports)
Exercise 2: Add an Item to a Set
Add "volleyball" to the set sports
and print the updated set.
Python
# Your code here
sports.add("volleyball")
print(sports)
Exercise 3: Remove an Item from a Set
Remove "tennis" from the set sports
and print the updated set.
Python
# Your code here
sports.remove("tennis")
print(sports)
Exercise 4: Find the Union of Two Sets
Find the union of the set sports
and another set containing "baseball" and "hockey", then print the result.
Python
# Your code here
other_sports = {"baseball", "hockey"}
all_sports = sports.union(other_sports)
print(all_sports)
Exercise 5: Find the Intersection of Two Sets
Find the intersection of the set all_sports
and another set containing "soccer" and "hockey", then print the result.
Python
# Your code here
common_sports = all_sports.intersection({"soccer", "hockey"})
print(common_sports) # Output should be {"soccer", "hockey"}
Import Links
Here are some useful import links for further reading: