Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
119 views
in Python by (114k points)
How to iterate over a set in Python?

Please log in or register to answer this question.

1 Answer

0 votes
by (114k points)

You can iterate over a set in Python using a for loop. 

Here's an example:

my_set = {1, 2, 3, 4, 5}
for element in my_set:
    print(element)
 

Output:

1
2
3
4
5
 

In the above code, we create a set called my_set and use a for loop to iterate over each element of the set. The loop prints each element on a separate line.

Note that since sets are unordered, the order in which the elements are printed may vary. If you need to print the elements of a set in a specific order, you can convert the set to a list and sort the list before iterating over it. 

Here's an example:

my_set = {3, 1, 4, 2, 5}
my_list = sorted(list(my_set))
for element in my_list:
    print(element)
 

Output:

1
2
3
4
5
 

In the above code, we first convert the set my_set to a list using the list() function, and then sort the list using the sorted() function. We then use a for loop to iterate over each element of the sorted list and print it.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...