Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Accessing Elements in a Set: Iteration and Membership Testing | Mastering Python Sets
Python Data Structures

book
Accessing Elements in a Set: Iteration and Membership Testing

Because sets are unordered, you cannot access their elements by index like you would with a list or tuple. However, you can:

  • Check for the existence of an element using the in keyword;
  • Iterate through the elements using a for loop.

Verifying Membership with in

The in keyword allows you to check if a specific element exists within a set:

# Define a set of favorite movies
movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"}

# Check if specific movies are in the set
is_inception_present = "Inception" in movies # True
is_avatar_present = "Avatar" in movies # False

# Print results
print(is_inception_present) # Output: True
print(is_avatar_present) # Output: False
12345678910
# Define a set of favorite movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"} # Check if specific movies are in the set is_inception_present = "Inception" in movies # True is_avatar_present = "Avatar" in movies # False # Print results print(is_inception_present) # Output: True print(is_avatar_present) # Output: False
copy

In this example, we use the in keyword to check if specific movies are present in the movies set and store the result as a boolean value in variables is_inception_present and is_avatar_present.

Iterating Through a Set with a for Loop

You can iterate over a set using a for loop to process each element individually. Since sets are unordered, the iteration order is unpredictable.

# Define a set of favorite movies
movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"}

# Iterate through the set and print each movie title
print("Movie collection:")
for movie in movies:
print(movie)
1234567
# Define a set of favorite movies movies = {"Inception", "Interstellar", "Tenet", "Dunkirk", "Memento"} # Iterate through the set and print each movie title print("Movie collection:") for movie in movies: print(movie)
copy

Each element in the set is accessed once during iteration. The order of elements in the output may vary.

Task

Swipe to start coding

You are given a fairly large set of the most popular movies.

  • Assign a boolean value to the variable is_first_movie_present to check if the movie "The Green Mile" is in the set.
  • Assign a boolean value to the variable is_second_movie_present to check if the movie "Titanic" is in the set.
  • Assign a boolean value to the variable is_third_movie_present to check if the movie "Interstellar" is in the set.
  • Use the in keyword to accomplish this task.

Solution

movies = {'The Shawshank Redemption', 'The Godfather', 'The Dark Knight', 'Pulp Fiction', 'Forrest Gump', 'Inception', 'Fight Club', 'The Matrix', 'The Lord of the Rings: The Return of the King', 'Star Wars: Episode IV - A New Hope', 'The Empire Strikes Back', 'The Godfather: Part II', 'Goodfellas', 'The Dark Knight Rises', 'The Silence of the Lambs', 'Schindler\'s List', 'City of God', 'The Usual Suspects', 'Seven Samurai', 'The Lion King', 'The Departed', 'Interstellar', 'Gladiator', 'Terminator 2: Judgment Day', 'Back to the Future', 'Casablanca', 'The Prestige', 'The Green Mile', 'The Shining', 'The Intouchables', 'The Pianist', 'Léon: The Professional', 'The Lord of the Rings: The Fellowship of the Ring', 'Pulp Fiction', 'Whiplash', 'The Wolf of Wall Street', 'The Revenant', 'The Social Network', 'The Terminator', 'The Big Lebowski', 'Saving Private Ryan', 'A Clockwork Orange', 'The Grand Budapest Hotel', 'The Incredibles', '12 Angry Men', 'The Hunt', 'The Conjuring'}

# Write your code here
is_first_movie_present = "The Green Mile" in movies

is_second_movie_present = "Titanic" in movies

is_third_movie_present = "Interstellar" in movies

# Testing
print(f"Presence of movies in the set:\nThe Green Mile: {is_first_movie_present};\nTitanic: {is_second_movie_present};\nInterstellar: {is_third_movie_present}.")
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 4
movies = {'The Shawshank Redemption', 'The Godfather', 'The Dark Knight', 'Pulp Fiction', 'Forrest Gump', 'Inception', 'Fight Club', 'The Matrix', 'The Lord of the Rings: The Return of the King', 'Star Wars: Episode IV - A New Hope', 'The Empire Strikes Back', 'The Godfather: Part II', 'Goodfellas', 'The Dark Knight Rises', 'The Silence of the Lambs', 'Schindler\'s List', 'City of God', 'The Usual Suspects', 'Seven Samurai', 'The Lion King', 'The Departed', 'Interstellar', 'Gladiator', 'Terminator 2: Judgment Day', 'Back to the Future', 'Casablanca', 'The Prestige', 'The Green Mile', 'The Shining', 'The Intouchables', 'The Pianist', 'Léon: The Professional', 'The Lord of the Rings: The Fellowship of the Ring', 'Pulp Fiction', 'Whiplash', 'The Wolf of Wall Street', 'The Revenant', 'The Social Network', 'The Terminator', 'The Big Lebowski', 'Saving Private Ryan', 'A Clockwork Orange', 'The Grand Budapest Hotel', 'The Incredibles', '12 Angry Men', 'The Hunt', 'The Conjuring'}

# Write your code here
is_first_movie_present = ___

is_second_movie_present = ___

is_third_movie_present = ___

# Testing
print(f"Presence of movies in the set:\nThe Green Mile: {is_first_movie_present};\nTitanic: {is_second_movie_present};\nInterstellar: {is_third_movie_present}.")
toggle bottom row
some-alt