Python Practice › Set Programs › Program 41
"Index" of an element in a set
Write a Python program to find the position of an element in a set.
Input
{30, 10, 20}, element 20Output
[10, 20, 30] 1
Approach
- Sets have no index. Sort into a list first, then use
index().
Solution
s = {30, 10, 20}ordered = sorted(s)print(ordered, ordered.index(20))Output
[10, 20, 30] 1
Note
A set is unordered, so a position only means something after you convert it to a sorted list.
Learn the concept
New to this topic? Read the lesson, then come back.