Looping Through Sets in Python: Iterating Over Set Elements

thumb_up 1  ·  sell Python set iteration, Iterating over a Python set, Looping through elements in Python 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}


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

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back