Python Program to Iterate Set Items

Write a Python program to Iterate Set Items. The Python for loop is the most common one to iterate over set items. In this example, we used for loop to iterate both the numeric and string set.

# Itearte Over Sets

set1 = {10, 20, 30, 40, 50, 60}

print("The Total Items in this Set = ")
for val in set1:
    print(val, end = ' ')


set2 = set("Tutorial Gateway")

print("The Total Items in this Set = ")
for char in set2:
    print(char, end = ' ')
Python Program to Iterate Set Items

Python Program to Iterate Set Items

Here, we converted the set to lists and used the for loop range to iterate and print set items based on the index.

# Itearte Over Sets

set1 = {11, 33, 55, 77, 99, 111}

list1 = list(set1)

print("The Total Items in this Set = ")
for i in range(len(list1)):
    print(list1[i], end = ' ')


set2 = set("TutorialGateway")
list2 = list(set2)

print("\n\nThe Total Items in this Set = ")
for i in range(len(list2)):
    print(list2[i], end = ' ')

Iterating set items using for loop output

The Total Items in this Set = 
33 99 55 11 77 111 

The Total Items in this Set = 
l r G w u i y o t a e T 

This Python program uses the enumerate to iterate the set items. Generally, we don’t need the id. So you can use the for _, value in enumerate(setName).

# Itearte Over Sets

set1 = {11, 33, 55, 77, 99, 111}

print("The Total Items in this Set = ")
for i, value in enumerate(set1):
    print(i, value)

set2 = set("Python")

print("\nThe Total Items in this Set = ")
for i, value in enumerate(set2):
     print(i, value)


print("\nThe Total Items in this Set = ")
for _, value in enumerate(set1):
    print(value, end = '  ')

print("\nThe Total Items in this Set = ")
for _, value in enumerate(set2):
     print(value, end = '  ')

Iterating set values enumerate output

The Total Items in this Set = 
0 33
1 99
2 55
3 11
4 77
5 111

The Total Items in this Set = 
0 y
1 o
2 n
3 t
4 P
5 h

The Total Items in this Set = 
33  99  55  11  77  111  
The Total Items in this Set = 
y  o  n  t  P  h  

It is another example of iterating over sets using list and list comprehension.

# Itearte Over Sets

set1 = {5, 10, 20, 25, 30, 35, 40}

print("The Total Items in this Set = ")
x = [print(val, end = ' ') for val in set1]

set2 = set("Python")

print("The Total Items in this Set = ")
x = list(val for val in set2)
print(x)
print(*x)

Iterating set items using list comprehension output

The Total Items in this Set = 
35 20 5 40 25 10 30 The Total Items in this Set = 
['h', 'P', 'y', 'o', 't', 'n']
h P y o t n