Hi everyone, welcome back. In this example, we will be going over how to loop through sets in Python. Sets can be used to store a collection of data. A set in Python does not allow duplicate values. The elements within a set are immutable, though elements can still be added or removed. The elements within a set are unordered and unindexed. With this introduction out of the way, let’s get into it.
Creating Set
Let’s start by creating our set:
mySet = {1, 2, 3}
print(mySet)Output:
{1, 2, 3}
So now, we have a populated set with a few elements. We can verify that it was successfully created and populated by printing the set and checking the output. Now let’s see how we can loop through the set.
For Loop
Let’s try to use a for loop to iterate through the set and print each element individually. Let’s see an example:
mySet = {1, 2, 3}for x in mySet:
print(x)Output:
1
2
3
As we can see in the example above, we used a for loop to iterate through the set. With each iteration, we printed the corresponding element to verify that we are successfully iterating through each element individually.
Conclusion
That is it for looping through sets in Python. We covered how to iterate through a set by using a for loop. We are unable to use a while loop because sets are unindexed. I hope this helps. If there are any questions or comments, please let me know. Thanks for reading.