Write a Python program to iteration over sets


The program demonstrates how to create sets in Python using numbers and strings.

The first set num is created using the set() constructor and passing a list of numbers as an argument. The elements in the set are unique and unordered, so the order in which they are printed may be different each time the program is run. The for loop is used to iterate over the elements in the set, and the end=' ' argument of the print() function is used to print each element on the same line, separated by a space.

The second set ch is created using the set() constructor and passing a string as an argument. The elements in the set are unique and unordered characters from the string. The for loop is used to iterate over the elements in the set, and the end=' ' argument of the print() function is used to print each element on the same line, separated by a space. In both cases, the sets are printed to the console to show the contents of the sets.

Source Code

print("\nCreating a set using Number:")
num = set([10,40,60,20,80,50])
for n in num:
  print(n, end=' ')
 
print("\n\nCreating a set using String:")
ch = set("Tutor Joes")  
for c in ch:
    print(c, end=' ')

Output

Creating a set using Number:
40 10 80 50 20 60

Creating a set using String:
J o t u r e s   T