Tuesday, 6 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...