Back to Python
2025-12-265 min read

Iterate Over a Set in Python

Learn Iterate Over a Set in Python step by step with clear examples and exercises.

Title: Iterate Over a Set in Python

Why This Matters

Iterating over collections is a fundamental concept in programming, enabling us to traverse through and manipulate data structures. In Python, we can iterate over various data types like lists, tuples, sets, and dictionaries. Today, we will focus on iterating over a set in Python. This skill is essential for solving real-world problems, debugging code, and preparing for interviews.

Iterating over a set allows us to perform operations on each element individually, making it easier to filter, sort, or calculate statistics. In this lesson, you will learn how to iterate over a set in Python using various techniques and examples.

Prerequisites

Before delving into the core concept, you should have a basic understanding of the following:

  1. Python syntax and variables
  2. Basic data structures in Python (lists, tuples, sets)
  3. Looping constructs in Python (for loops, while loops, enumerate function)
  4. Conditional statements (if-else)
  5. Arithmetic operations and modulus operator (%)
  6. String formatting (f-strings or print function with end parameter)
  7. Understanding the concept of unordered collections and unique elements in sets
  8. Basic set operations like union, intersection, difference, and symmetric difference

Core Concept

A set is an unordered collection of unique elements. In Python, we can create a set using curly braces {}, the set() constructor, or the built-in set() function. To iterate over a set in Python, we use a for loop. Here's a simple example:

my_set = {1, 2, 3, 4, 5}
for element in my_set:
print(element)

In this code snippet, we create a set named my_set containing the numbers from 1 to 5. Then, we use a for loop to iterate over each element in the set and print it.

Worked Example

Let's consider a more complex example where we need to calculate the sum of all even numbers in a set:

my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}
even_sum = 0

for element in my_set:
if element % 2 == 0:
even_sum += element

print(f"The sum of all even numbers is {even_sum}")

In this example, we create a set my_set containing the numbers from 1 to 9. We initialize a variable even_sum to store the sum of all even numbers in the set. Then, we use a for loop to iterate over each element in the set. If an element is even (i.e., its remainder when divided by 2 is zero), we add it to even_sum. Finally, we print the calculated sum using f-string formatting.

Common Mistakes

  1. Forgetting to check if an element is even before adding it to the sum:
my_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}
sum = 0

for element in my_set:
sum += element

print(f"The sum of all elements is {sum}")

In this code snippet, we forget to check if an element is even before adding it to the sum. As a result, the output will include odd numbers as well, which leads to an incorrect sum.

  1. Using a while loop instead of a for loop:
my_set = {1, 2, 3, 4, 5}
i = 0
even_sum = 0

while i < len(my_set):
element = my_set[i]
if element % 2 == 0:
even_sum += element
i += 1

print(f"The sum of all even numbers is {even_sum}")

In this example, we use a while loop to iterate over the set. This approach is less common and more error-prone compared to using a for loop. It's essential to stick with Python's recommended idioms to write cleaner, more readable code.

Subheadings under Common Mistakes:

Using a while loop with enumerate function

my_set = {1, 2, 3, 4, 5}
i, even_sum = 0, 0

while i < len(my_set):
element, _ = next(enumerate(my_set))
if element % 2 == 0:
even_sum += element
i += 1

print(f"The sum of all even numbers is {even_sum}")

In this example, we use a while loop with the enumerate function to iterate over the set. This approach is less efficient and harder to read compared to using a for loop. It's recommended to stick with the for loop when iterating over collections in Python.

Practice Questions

  1. Write a Python program that calculates the sum of all odd numbers in a set containing the numbers from 1 to 20.
odd_sum = 0
my_set = set(range(1, 21))
for element in my_set:
if element % 2 != 0:
odd_sum += element
print(f"The sum of all odd numbers is {odd_sum}")
  1. Given a set my_set = {3, 5, 7, 9, 11}, write a Python program that multiplies each number by 2 and stores the result in another set called doubled_set.
doubled_set = set()
my_set = {3, 5, 7, 9, 11}
for element in my_set:
doubled_set.add(element * 2)
print("The doubled set is", doubled_set)

FAQ

  1. Can I use a for loop to iterate over a set in reverse order?

Yes, you can use the built-in reversed() function to iterate over a set in reverse order:

my_set = {1, 2, 3, 4, 5}
for element in reversed(list(my_set)):
print(element)
  1. What happens if I try to add a duplicate element to a set?

When you try to add a duplicate element to a set, Python automatically removes the duplicate and only keeps one copy of the element in the set.

  1. How can I find the largest or smallest element in a set without sorting it?

Since sets are unordered collections, there is no built-in way to find the largest or smallest element directly. However, you can convert the set to a list, sort it, and then access the first or last element of the sorted list:

my_set = {5, 2, 8, 1, 9}
my_list = list(my_set)
sorted_list = sorted(my_list)
print("The smallest number in the set is", sorted_list[0])
print("The largest number in the set is", sorted_list[-1])
  1. How can I find the union, intersection, difference, and symmetric difference of two sets?

To perform set operations like union, intersection, difference, and symmetric difference, you can use the built-in methods union(), intersection(), difference(), and symmetric_difference(). Here's an example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)
difference_set = set1.difference(set2)
symmetric_difference_set = set1.symmetric_difference(set2)
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference:", difference_set)
print("Symmetric Difference:", symmetric_difference_set)
Iterate Over a Set in Python | Python | XQA Learn