I'm searching for the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is? I know that all values in the list are unique like my example.
The first method I try is (3.8sec in my real code):
a = [4,2,3,1,5,6]
if a.count(7) == 1:
b=a.index(7)
"Do something with variable b"
The second method I try is (2x faster:1.9sec on my real code):
a = [4,2,3,1,5,6]
try:
b=a.index(7)
except ValueError:
"Do nothing"
else:
"Do something with variable b"
Proposed methods from Stackoverflow user (2.74sec on my real code):
a = [4,2,3,1,5,6]
if 7 in a:
a.index(7)
In my real code, first method takes 3.81sec and the second method takes 1.88sec. It's a good improvement but:
I'm a beginner with Python/scripting and I want to know if a fastest way exists to do the same things and save more process time?
More specific explication for my application:
In the API of blender a can access to a list of particles:
particles = [1,2,3,4...etc.]
From there, I can access to its location:
particles[x].location = [x,y,z]
And I test for each particle if a neighbour exists by searching in the location of each particle like:
if [x+1,y,z] in particles.location
"find the identity of this neighbour particles in x:the index
of the particles array"
particles.index([x+1,y,z])

bisectmodule – Steven Rumbalski Sep 27 '11 at 15:27