numbers = {2, 0, 1}
print(numbers){0, 1, 2}
A set stores a collection of unique items. Sets are useful when you want to remove duplicates, check membership, or compare groups of items.
Create a set by placing comma-separated items inside curly brackets {}.
numbers = {2, 0, 1}
print(numbers){0, 1, 2}
The displayed order may differ from the order used to create the set.
print(type(numbers))<class 'set'>
Use set() to create an empty set.
empty_set = set()
print(empty_set)set()
print(type(empty_set))<class 'set'>
Empty curly brackets create a dictionary, which we will study in the next session.
empty_brackets = {}
print(type(empty_brackets))<class 'dict'>
Use set(), not {}, when you need an empty set.
A set can contain immutable values such as strings, numbers, booleans, and tuples.
voters = {"Alan", "Louis", "Juan", "Lucy"}
print(voters){'Alan', 'Juan', 'Lucy', 'Louis'}
room_numbers = {101, 205, 310, 412}
print(room_numbers){101, 412, 205, 310}
In Python, True behaves like 1, and False behaves like 0. Since sets remove equivalent values, this set contains only two items.
answers = {True, False, 1, 0, True}
print(answers){False, True}
Tuples can be stored in a set if all their items are also immutable.
reserved_seats = {("A", 1), ("A", 2), ("B", 1)}
print(reserved_seats){('A', 1), ('B', 1), ('A', 2)}
Different immutable types can appear in the same set.
mixed_values = {1, "Hello", (0, 0)}
print(mixed_values){'Hello', 1, (0, 0)}
Lists cannot be stored in a set because lists are mutable.
invalid_set = {"room A", ["Maya", "Leo"]}TypeError: unhashable type: 'list'
Sets do not preserve item positions. Therefore, they cannot be indexed or sliced.
colors = {"blue", "green", "red"}
print(colors){'green', 'red', 'blue'}
print(colors[0])TypeError: 'set' object is not subscriptable
Use the in operator when you want to check whether a value belongs to a set.
print("green" in colors)True
Write two expressions using in:
"Python" appears in completed_courses."Design" appears in completed_courses.completed_courses = {"Python", "Economics", "Statistics"}print("Python" in completed_courses)print("Design" in completed_courses)Sets are mutable. Methods such as add() and remove() change the original set in place.
attendees = {"Maya", "Leo", "Nora"}
print(attendees){'Leo', 'Maya', 'Nora'}
attendees.add("Sam")
print(attendees){'Leo', 'Maya', 'Nora', 'Sam'}
attendees.remove("Leo")
print(attendees){'Maya', 'Nora', 'Sam'}
remove() raises an error if the value is absent. discard() removes the value only if it exists.
attendees.discard("Alex")
print(attendees){'Maya', 'Nora', 'Sam'}
Sets keep only one copy of each value.
votes = {"film", "film", "music", "games", "music"}
print(votes){'music', 'games', 'film'}
Capitalization matters because Python treats "hello" and "Hello" as different strings.
words = {"Hello", "hello", "World"}
print(words){'Hello', 'hello', 'World'}
Convert the list below to a set and print the result.
usernames = ["alex", "maya", "alex", "sam", "maya"]usernames = ["alex", "maya", "alex", "sam", "maya"]
unique_usernames = set(usernames)
print(unique_usernames)Set operations make it easy to combine and compare collections.
film_club = {"Ava", "Leo", "Nora", "Sam"}
book_club = {"Nora", "Sam", "Iris", "Omar"}
print(film_club){'Leo', 'Ava', 'Nora', 'Sam'}
print(book_club){'Omar', 'Iris', 'Nora', 'Sam'}
The union contains every item that appears in either set. Use | or .union().
all_members = film_club | book_club
print(all_members){'Ava', 'Leo', 'Iris', 'Nora', 'Omar', 'Sam'}
The method form gives the same result:
all_members = film_club.union(book_club)The intersection contains only items that appear in both sets. Use & or .intersection().
members_of_both = film_club & book_club
print(members_of_both){'Nora', 'Sam'}
The method form gives the same result:
members_of_both = film_club.intersection(book_club)The difference contains items from the first set that do not appear in the second. Use - or .difference().
film_only = film_club - book_club
print(film_only){'Leo', 'Ava'}
The order matters. Reversing the sets produces a different result.
book_only = book_club - film_club
print(book_only){'Omar', 'Iris'}
The symmetric difference contains items that appear in exactly one of the sets. Use ^ or .symmetric_difference().
members_of_one_club = film_club ^ book_club
print(members_of_one_club){'Ava', 'Leo', 'Iris', 'Omar'}
Without running the code, determine the contents of each result.
streaming_a = {"Arrival", "Dune", "Moonlight"}
streaming_b = {"Dune", "Past Lives", "Moonlight"}
available_anywhere = streaming_a | streaming_b
available_on_both = streaming_a & streaming_b
only_on_a = streaming_a - streaming_bprint(available_anywhere)This contains "Arrival", "Dune", "Moonlight", and "Past Lives".
print(available_on_both)This contains "Dune" and "Moonlight".
print(only_on_a)This contains only "Arrival".
Three friends propose guests for a party. Write a program that finds:
friend_1 = {"Alice", "Emma", "Charlie", "David", "Louis"}
friend_2 = {"Charlie", "David", "Emma", "Frank", "Juan"}
friend_3 = {"David", "Emma", "Alice", "Helen", "Julia"}all_guests = friend_1 | friend_2 | friend_3
common_guests = friend_1 & friend_2 & friend_3
only_friend_1 = friend_1 - (friend_2 | friend_3)
only_friend_2 = friend_2 - (friend_1 | friend_3)
only_friend_3 = friend_3 - (friend_1 | friend_2)print(f"All guests: {all_guests}")print(f"Common guests: {common_guests}")print(f"Only friend 1: {only_friend_1}")print(f"Only friend 2: {only_friend_2}")print(f"Only friend 3: {only_friend_3}")Fix the code so it finds words present in both sets, regardless of capitalization.
set_1 = {"TABle", "DOOR", "chain", "wire"}
set_2 = {"pencil", "door", "taBle", "word"}
common_words = set_1 & set_2
print(common_words)Create two new sets containing lowercase versions of the words. This is a set comprehension.
lowercase_1 = {word.lower() for word in set_1}
lowercase_2 = {word.lower() for word in set_2}
common_words = lowercase_1 & lowercase_2
print(common_words)Use list(), tuple(), and set() to convert between these data structures.
number_list = [1, 2, 2, 3]
print(number_list)[1, 2, 2, 3]
print(type(number_list))<class 'list'>
number_tuple = tuple(number_list)
print(number_tuple)(1, 2, 2, 3)
print(type(number_tuple))<class 'tuple'>
Converting to a set removes duplicate items.
number_set = set(number_list)
print(number_set){1, 2, 3}
print(type(number_set))<class 'set'>
Converting a set back to a list does not restore its original order.
unique_number_list = list(number_set)
print(unique_number_list)[1, 2, 3]
Each friend has a list of movies they would like to watch. Write a function named choose_movies() that returns the movies accepted by everyone.
friend_1 = ["Inception", "The Matrix", "Interstellar", "Avatar"]
friend_2 = ["The Godfather", "Interstellar", "Titanic", "Arrival"]
friend_3 = ["Interstellar", "Toy Story", "Arrival", "The Dark Knight"]
friend_4 = ["Interstellar", "Star Wars", "Arrival", "The Avengers"]def choose_movies(friend_1, friend_2, friend_3, friend_4):
common_movies = (
set(friend_1)
& set(friend_2)
& set(friend_3)
& set(friend_4)
)
return list(common_movies)print(choose_movies(friend_1, friend_2, friend_3, friend_4))Write a function named collect_movies() that returns a list containing every proposed movie without duplicates.
def collect_movies(friend_1, friend_2, friend_3, friend_4):
all_movies = (
set(friend_1)
| set(friend_2)
| set(friend_3)
| set(friend_4)
)
return list(all_movies)print(collect_movies(friend_1, friend_2, friend_3, friend_4))| Data structure | Syntax | Ordered | Mutable | Duplicates |
|---|---|---|---|---|
| List | [] |
Yes | Yes | Yes |
| Tuple | () |
Yes | No | Yes |
| Set | {} or set() |
No | Yes | No |
Use a list when order matters and the collection may change. Use a tuple when order matters and the collection should remain fixed. Use a set when uniqueness and membership matter more than order.
set().Work through the “Sets” homework exercises available here. To earn participation credit, complete the exercises highlighted in red.