Python – Loop Sets
In Python, a set is an unordered collection of unique elements. It is represented by curly braces ({}) and can be used to store multiple items. Looping through a set allows you to iterate over each element and perform certain operations. In this article, we will explore how to loop through sets in Python with examples.
1. Looping through a Set using a for Loop
The most common way to loop through a set is by using a for loop. This allows you to iterate over each element in the set and perform specific actions or operations.
Here’s an example:
fruits = {"apple", "banana", "orange"}
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
In the above example, we have a set called “fruits” which contains three elements: “apple”, “banana”, and “orange”. Using a for loop, we iterate over each element in the set and print it.
2. Looping through a Set using a while Loop
Another way to loop through a set is by using a while loop. This allows you to iterate over the set until a certain condition is met.
Here’s an example:
fruits = {"apple", "banana", "orange"}
iterator = iter(fruits)
while True:
try:
fruit = next(iterator)
print(fruit)
except StopIteration:
break
Output:
apple
banana
orange
In the above example, we create an iterator object using the iter() function and pass the set “fruits” as an argument. Then, we use a while loop to iterate over the set until a StopIteration exception is raised, indicating that we have reached the end of the set.
3. Looping through a Set using List Comprehension
List comprehension is a concise way to create lists in Python. It can also be used to loop through a set and perform certain operations.
Here’s an example:
fruits = {"apple", "banana", "orange"}
uppercased_fruits = [fruit.upper() for fruit in fruits]
print(uppercased_fruits)
Output:
['APPLE', 'BANANA', 'ORANGE']
In the above example, we use list comprehension to iterate over each element in the set “fruits” and convert it to uppercase. The resulting list, “uppercased_fruits”, contains the uppercase versions of the elements in the set.
Conclusion
Looping through sets in Python allows you to iterate over each element and perform specific operations. Whether you use a for loop, a while loop, or list comprehension, the key is to understand the structure of sets and how to access their elements. By mastering this concept, you can effectively work with sets and manipulate their contents according to your needs.