Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Iteration Over Sets
Title :
Write A Python Program To Iteration Over Sets
Description :
Hey Guys, In this article let me explain to you how to remove duplicate elements out of a python list data structure.
Set is an unordered collection of unique elements. In this blog, we will explore how to iterate over sets in Python and take it a step further by incorporating user input to create interactive and dynamic programs.
Then try to iterate all the elements of the set and then print it on to standard output, let's only use for loop.
Note: We cannot use while loop for iterating a set because set data structure is referred as Unordered Collections of Unique Elements and that doesn't support operations like indexing or slicing etc
length = int(input("Enter Set Length : "))
myset = set()
for _ in range(length):
temp = int(input("Enter Set Item : "))
myset.add(temp)
Lets ask the user the enter set length, then use the for loop to iterate from 0 to set length, while we iterate keep asking user to enter the set item and add it to the set.
for item in myset:
print(item)
Use the for loop to iterate all the items present in the set and print all the items present in the set using the print function call.
Complete Python Code :
length = int(input("Enter Set Length : "))
myset = set()
for _ in range(length):
temp = int(input("Enter Set Item : "))
myset.add(temp)
for item in myset:
print(item)
Output :
Enter Set Length : 5
Enter Set Item : 1
Enter Set Item : 2
Enter Set Item : 1
Enter Set Item : 2
Enter Set Item : 1
1
2
Output :
Enter Set Length : 5
Enter Set Item : 1
Enter Set Item : 2
Enter Set Item : 3
Enter Set Item : 1
Enter Set Item : 4
1
2
3
4
Conclusion :
In this blog, we discussed how to write a python program to iterate a set using a for loop.
Understanding sets and iteration is essential for efficiently working with collections of unique elements in Python.
Iteration is a process of accessing each element of a collection (like a set) in a sequence, one after the other.
We are using only a for loop to print the elements of set, comment down if you have any queries related to the above python program.
0 Comments