0

I use python and I have a list of numbers and I would like to search a number X but I must find the second one element and if it doesn't exist I must get a msg

Example:

list: [5, 6, 8, 7, 9, 6, 7, 9, 2, 4, 6, 8]

X = 6

return: i = 5

Ps: I need the faster code because I need to repeat it in a loop of 200000 i

rima
  • 13
  • 4
  • In question you are asking 2nd element and in return statement you have return 1st element. Please be little more clear. – Hayat Jun 26 '19 at 09:51
  • He is returning the index. And it's correct because the index of the second 6 is 5 – Paolo Mossini Jun 26 '19 at 09:53
  • Yes exactly paolo, I search the number 6, in the list the first element has an index 1 and the second have i = 5 – rima Jun 26 '19 at 09:56
  • I provide you an answer, let me know if it works – Paolo Mossini Jun 26 '19 at 09:59
  • you can use python multiprocessing on top of the optimized code if the machine is a multiprocessor. I suggest this because all results are independent for every loop you are processing and you have 200000 iterations. – pranav prashant Jun 26 '19 at 10:27

1 Answers1

0

A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]

And then you get the second element of the result array

Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23