Python Practice › Set Programs › Program 41

"Index" of an element in a set

EasySet Programs · 41 of 48

Write a Python program to find the position of an element in a set.

Advertisement
Input
{30, 10, 20}, element 20
Output
[10, 20, 30] 1

Approach

  1. Sets have no index. Sort into a list first, then use index().

Solution

Python
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.

More set programs

← All 48 Set Programs

Leave a Comment