Python - Loop Sets


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 1

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

Example 2

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.

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}
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements