Last Updated on May 9, 2024 by Roshan Parihar
To get elements from Set in Python, use the for
loop of Python to access each element of Set and print them in the output.
You can also find the smallest and largest element in a Set with min()
and max()
functions in Python.
How to Get Elements From Set Using For Loop in Python
If you want to get an element from Set, you can use the for
loop of Python that traverses through each element. You can use the if condition to match with the element and print the result.
Examples 1
1 2 3 4 5 6 |
#declare Set in Python mySet = {"Ram", "Shyam", 10, "Bilal", 13.2, "Feroz"} #Get elements from a Set and print the result for x in mySet: print(x) |
Output
13.2
Bilal
Feroz
Shyam
Ram
The above example prints each element one by one with one element at one line. The elements get printed on each iteration over Set elements in Python.
Using print() to Get Matching Element in a Set in Python
If you want to check the given element is present in the Set using Python. You can use the simple method that checks the element in a Set. It gives the result in boolean format (True
/False
). If the element is present in the Set, it gives True otherwise False.
Examples 2
1 2 3 4 5 6 7 8 |
#declare Set in Python mySet = {"Ram", "Shyam", 10, "Bilal", 13.2, "Feroz"} #Given element to check in a set Item = "Shyam" #Print result print(Item in mySet) |
Output
The output in the above example shows that the specified element is present in the Set. The example checks a single element at a time in the Set variable.
Get Smallest and Largest Elements in Python
You can find the smallest value from the Set variable using the min()
function. It takes a single argument as the Set variable to get the lowest element from it. The Set variable contains all the elements in numeric format.
Examples 3
1 2 3 4 5 6 7 8 |
#declare Set in Python mySet = {17, 11, 10, 3, 21, 9} #Get the smallest element in a set smallItem = min(mySet) #Print result print(smallItem) |
Output
The above example contains an output that shows that 3 is the smallest item in the given Set variable.
Find Largest Value Item in a Numeric Set Using Python
The largest value can be retrieved from a Set using the max()
function. It takes a set variable as its argument to retrieve the largest numeric value from it.
Examples 4
1 2 3 4 5 6 7 8 |
#declare Set in Python mySet = {17, 11, 10, 3, 21, 9} #Get the largest element in a set maxItem = max(mySet) #Print the largest element of a Set print(maxItem) |
Output
The above example shows that 21 is the largest value among all the elements of a Set.
You May Also Like to Read