How do you loop a set in python?

how do you loop a set
david_park
Asked Mar 27, 2015
Use this:
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
-----------------------------
Looping Through a String
Loop through the letters in the word "banana":

for x in "banana":
----------------------------------
The break Statement
With the break statement we can stop the loop before it has looped through all the items:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
print(x)

Prognoz technologies ( https://prognoztech.com/ ) is one the reputed python training institutes in Mumbai for best python learning.
prognoz
Answered Mar 24, 2021
BYSOS - India's Foremost Online Stock Fantasy Gaming Platform
bysos.in
BYSOS
Answered Mar 24, 2021
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.

There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variations. Let’s see all the different ways we can iterate over a set in Python. Learn For More OnlineITGuru

Analysis of each method:
For explaining the working of each way/technique, time per set(randomly generated set) has been calculated for 5-times to get a rough estimate on how much time every technique takes for iterating over a given set. random.seed(21) has been added to each script to fixate over the random numbers that are generated every time the program is executed. Using constant seed helps us to determine which technique is best for a given particular randomly generated set.

Method #1: Iterating over a set using simple for loop.


# Creating a set using string
test_set = set("geEks")

# Iterating using for loop
for val in test_set:
print(val)
mahesh32
Answered Mar 29, 2021

TIP: If it's not your answer to this question, please click "Leave a Comment" button under the question to communicate with the question owner.

Categories