How to get index of element in Set object
Question:
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 ?
Answers:
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.
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))
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 ?
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.
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))