Looping Through a Set

You can loop through the items of a set using a for loop, similar to other iterable objects.

Using a for Loop

Example: Iterating Over Set Items

# Looping through a set
names = {"Karthick AG", "Durai", "Vijay", "John"}
for name in names:
    print("Hello,", name + "!")

Output (Order may vary)

Hello, Vijay!

Hello, John!

Hello, Durai!

Hello, Karthick AG!

Explanation: The for loop iterates over each item in the set. Since sets are unordered, the items may be returned in any order.