Iterate over a set in Python

Iterate over a set in Python

Iterating over a set in Python is very straightforward and is similar to iterating over a list or a tuple. You can use a for loop.

Here's a basic example to illustrate:

# Creating a set fruits = {"apple", "banana", "cherry"} # Iterating over the set for fruit in fruits: print(fruit) 

Output:

apple banana cherry 

Keep in mind that sets are unordered collections, so the order in which you inserted elements might not be the same as the order in which they are iterated over.

Another point to remember is that sets do not allow duplicate values, so if you add a duplicate item to the set and then iterate over it, you'll only see it once.


More Tags

windows-10 statelesswidget libusb-1.0 nw.js file-put-contents cdi launch4j pi binaryfiles stylesheet

More Programming Guides

Other Guides

More Programming Examples