All Courses

How to write a program for iteration over sets?

By Manerushi149@gmail.com, 3 months ago
  • Bookmark
0

How to write a program for iteration over sets?

Python
Sets
Iteration
2 Answers
0
Hitendradixit18@gmail.com

Hint:

Step 1: Declare a set 

Step 2: iterate over set like(for i in set1 )

Step 3 :print(i)

0
Goutamp777

To iterate over the elements of a set, you can use a for loop. Here is an example:

# Define a set
my_set = {1, 2, 3, 4}


# Iterate over the elements of the set
for element in my_set:
  print(element)

This will print the elements of the set one per line:

1
2
3
4

You can also use the for loop to iterate over the elements of a set in combination with the enumerate function, which gives you both the index and the value of each element in the set:

# Define a set
my_set = {1, 2, 3, 4}


# Iterate over the elements of the set with their indices
for index, element in enumerate(my_set):
  print(f'{index}: {element}')

This will print the elements of the set along with their indices:

0: 1
1: 2
2: 3
3: 4


Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More