Yaboku
Yaboku

Reputation: 212

Set indexing python

Can we do indexing in a python set, to attain an element from a specific index? Like accessing a certain element from the below set:

st = {'a', 'b', 'g'}

How to return the second element by indexing?

Upvotes: 6

Views: 29323

Answers (5)

ecp
ecp

Reputation: 2429

If you have influence on the construction of the set, you can create a dictionary instead of that set where each value of the original set is the key to your index or vice versa whatever suits the need.

>>>{key:i for i,key in enumerate(st)}
{'g': 0, 'a': 1, 'b': 2}

>>>{i:key for i,key in enumerate(st)}
{0: 'g', 1: 'a', 2: 'b'}

Upvotes: 0

I159
I159

Reputation: 31199

You want to get a subset using indexes. set is an unordered collection with non-duplicated items. The set's pop method removes a random item from the set. So, it is impossible in general, but if you want to remove a limited number of random items (I can't imagine why anybody needs it), you can call pop multiple times in a loop.

Upvotes: 0

noobita
noobita

Reputation: 65

In addition to @learner8269 's answer, if you just need the index of a particular element (for some unknown reasons of life), you can get it using enumerate().

ele = 4
s = set(range(2,10))
for i,j in enumerate(s):
    if j == ele:
        break
print('Index of %d: %d'%(ele,i))

Upvotes: 1

anurag0510
anurag0510

Reputation: 763

As set is un-ordered we need to work around to get what is expected. Following code would do the job:

mySet = set([1, 2, 3])
list(mySet)[0]

This create a new list which contains each member of the set, It won't be a good choice if your set is really large.

Upvotes: -5

jrefior
jrefior

Reputation: 4431

No. A set is unordered by definition:

A set is an unordered collection with no duplicate elements.

Upvotes: 11

Related Questions