Tuesday, November 6, 2018

Python: finding an element in a list





What is a good way to find the index of an element in a list in Python?
Note that the list may not be sorted.



Is there a way to specify what comparison operator to use?


Answer



The best way is probably to use the list method .index.



For the objects in the list, you can do something like:



def __eq__(self, other):
return self.Value == other.Value



with any special processing you need.



You can also use a for/in statement with enumerate(arr)



Example of finding the index of an item that has value > 100.



for index, item in enumerate(arr):
if item > 100:

return index, item


Source


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...