Help Center

Looping Through Sets in Python: Iterating Over Set Elements

Python set iteration, Iterating over a Python set, Looping through elements in Python sets 1
Print

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}


The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Still need a hand?

Our support team is on standby if this article didn't fully answer your question.

« Back