Lolek
Lolek

Reputation: 511

How to get index of element in Set object

I have something like this:

numberList = {}
        for item in results:
            data = json.loads(item[0])
            if data[key] in itemList:
                numberList[itemList.index(data[key])] += 1
        print numberList

where itemList is 'set' object. How can I access index of single element in it ?

Upvotes: 47

Views: 175839

Answers (2)

Kirushikesh
Kirushikesh

Reputation: 748

Convert the set into list and you can use index() function in that list

Example:
x = {1,2,3};
x = list(x);
print(x.index(1)) 

Upvotes: 7

mculhane
mculhane

Reputation: 943

A set is just an unordered collection of unique elements. So, an element is either in a set or it isn't. This means that no element in a set has an index.

Consider the set {1, 2, 3}. The set contains 3 elements: 1, 2, and 3. There's no concept of indices or order here; the set just contains those 3 values.

So, if data[key] in itemList returns True, then data[key] is an element of the itemList set, but there's no index that you can obtain.

Upvotes: 80

Related Questions