Python - Loop Sets



Loop Through Set Items

A set in Python is not a sequence, nor is it a mapping type class. Hence, the objects in a set cannot be traversed with index or key. However, you can traverse each item in a set using a for loop.

Example

The following example shows how you can traverse through a set using a for loop −

langs = {"C", "C++", "Java", "Python"}
for lang in langs:
   print (lang)

It will produce the following output

C
Python
C++
Java

Loop Through Set Items with add() Method

The following example shows how you can run a for loop over the elements of one set, and use the add() method of set class to add in another set.

Example

s1={1,2,3,4,5}
s2={4,5,6,7,8}
for x in s2:
   s1.add(x)
print (s1)

It will produce the following output

{1, 2, 3, 4, 5, 6, 7, 8}
Advertisements