Table of Contents
ToggleLooping through set items in Python refers to iterating over each element in a set. We can later perform required operations on each item. These operations include printing elements, conditional operations, filtering elements, etc.
Unlike lists and tuples, sets are unordered collections, so the elements will be accessed in an arbitrary order. You can use a for loop to iterate through the items in a set.
A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.
In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through set items using a for loop by iterating over each item in the set.
for item in set:
# Code block to execute
# Defining a set with multiple elements
my_set = {25, 12, 10, -21, 10, 100}
# Loop through each item in the set
for item in my_set:
# Performing operations on each element
print("Item:", item)
Item: 100
Item: 25
Item: 10
Item: -21
Item: 12
A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to “True”.
We can loop through set items using a while loop by converting the set to an iterator and then iterating over each element until the iterator reaches the end of the set.
# Defining a set with multiple elements
my_set = {1, 2, 3, 4, 5}
# Converting the set to an iterator
set_iterator = iter(my_set)
# Looping through each item in the set using a while loop
while True:
try:
# Getting the next item from the iterator
item = next(set_iterator)
# Performing operations on each element
print("Item:", item)
except StopIteration:
# If StopIteration is raised, break from the loop
break
Item: 1
Item: 2
Item: 3
Item: 4
Item: 5
A set comprehension in Python is a concise way to create sets by iterating over an iterable and optionally applying a condition.
# Original list
numbers = [1, 2, 3, 4, 5]
# Set comprehension to create a set of squares of even numbers
squares_of_evens = {x**2 for x in numbers if x % 2 == 0}
# Print the resulting set
print(squares_of_evens)
{16, 4}
The enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element.
# Converting the set into a list
my_set = {1, 2, 3, 4, 5}
set_list = list(my_set)
# Iterating through the list
for index, item in enumerate(set_list):
print("Index:", index, "Item:", item)
Index: 0 Item: 1
Index: 1 Item: 2
Index: 2 Item: 3
Index: 3 Item: 4
Index: 4 Item: 5
The add() method in Python is used to add a single element to a set.
# Creating an empty set
my_set = set()
# Looping through a sequence and adding elements to the set
for i in range(5):
my_set.add(i)
print(my_set)
{0, 1, 2, 3, 4}
