I have list of 10000 random numbers. I want the elements and their corresponding index for that element in the list between 5 and 500. I got to get the element by simple code
elements = [x for x in list_10000 if 5 <= x <= 500]
And for getting index I did
element_index = [list_10000.index(x) for x in list_10000 if 5 <= x <= 500]
The above index code took a lot of time but didn't execute. I have tried with arange and enumerate. But they gave different numbers of values than what I got with len(elements)
How can I get index value ?? Any help would be great !! Thanking you in advance.
CodePudding user response:
You could use enumerate
:
element_index = [i for i, x in enumerate(list_10000) if 5 <= x <= 500]
CodePudding user response:
When you try to use index(1)
two times, it will give you the same result both times, so having duplicate values will produce the same index.
You could instead use a dictionary, and immediately write both the value and it's index:
{i: list_10000[i] for i in range(len(list_10000)) if 5 <= list_10000[i] <= 500}
This will create a dictionary, where the index is the key, and the value is your number at the index.