Iterating over a set in Python
What is Iteration? Iteration means accessing each element of a collection (such as a list, tuple, or set) one by one. Since a set in Python is an unordered collection (no index and no duplicate values), elements cannot be accessed using an index. Instead, a loop is used to traverse all elements.
Example: Using a for loop
Python
# Define a set
my_set = {"apple", "banana", "cherry"}
# Iterate through the set
for item in my_set:
print(item) Explanation
- The for loop picks each element from the set one by one.
- Elements are returned in an unpredictable order because sets are unordered.
Output banana
apple
cherry
Note: The output order may change every time you run the program because Python sets do not maintain insertion order.