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?
-
2Can unmark this one as duplicated, the questions and answers don't handle the case of class instances that match a criteria.Caveman– Caveman2020年06月22日 16:15:39 +00:00Commented Jun 22, 2020 at 16:15
-
1Also finding the index of an item in a list is not the same thing as finding the item in a list.mikemaccana– mikemaccana2021年02月05日 14:28:48 +00:00Commented Feb 5, 2021 at 14:28
10 Answers 10
From Dive Into Python:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
-
21But this code gives error when element is not in the list.In current example context if I search for 'three' (i.e: li.index('three')) gives error.Kedar.Aitawdekar– Kedar.Aitawdekar2014年05月28日 07:31:47 +00:00Commented May 28, 2014 at 7:31
-
12You can catch the error to detect when something isn't in the list.
try: li.index("three") except ValueError: found = false
Peter G– Peter G2016年11月18日 16:06:13 +00:00Commented Nov 18, 2016 at 16:06 -
2if you really want to find the index then, first check element in array if True then only do => li.index("example")yogesh mhetre– yogesh mhetre2019年12月04日 12:37:28 +00:00Commented Dec 4, 2019 at 12:37
If you just want to find out if an element is contained in the list or not:
>>> li
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> 'example' in li
True
>>> 'damn' in li
False
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
Here is another way using list comprehension (some people might find it debatable). It is very approachable for simple tests, e.g. comparisons on object attributes (which I need a lot):
el = [x for x in mylist if x.attr == "foo"][0]
Of course this assumes the existence (and, actually, uniqueness) of a suitable element in the list.
-
10
el = [x for x in mylist if x.attr == "foo"]
if el: do something with el[0]
solves the "existence" problemberkus– berkus2015年07月30日 16:33:45 +00:00Commented Jul 30, 2015 at 16:33 -
17
el = next((x for x in mylist if x.attr == "foo"), None)
if you want to receive a value even when doesn't existThiago Lages de Alencar– Thiago Lages de Alencar2021年02月08日 12:13:56 +00:00Commented Feb 8, 2021 at 12:13 -
2
[*[label_set for label_set in prediction_label_sets if x == 3], None][0]
If you want it to fallback to none, without using an iterator. Not sure if it's simpler or harder.Sebastian– Sebastian2022年01月26日 09:47:39 +00:00Commented Jan 26, 2022 at 9:47
assuming you want to find a value in a numpy array, I guess something like this might work:
Numpy.where(arr=="value")[0]
-
1doesn't work for multidimensional arrays if you're looking for a specific row, e.g.
arr = np.array([[0,0,1],[0,1,0],[1,0,0]])
if you donp.where(arr == [0,1,0])
it doesn't give the right resultierdna– ierdna2018年08月21日 22:11:04 +00:00Commented Aug 21, 2018 at 22:11 -
@ierdna, don't you need to supply
axis=0
oraxis=1
?mLstudent33– mLstudent332019年09月28日 08:17:06 +00:00Commented Sep 28, 2019 at 8:17
There is the index
method, i = array.index(value)
, but I don't think you can specify a custom comparison operator. It wouldn't be hard to write your own function to do so, though:
def custom_index(array, compare_function):
for i, v in enumerate(array):
if compare_function(v):
return i
I use function for returning index for the matching element (Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
And then it is quite easy and readable:
element = find_name(mylist,"my name")
The index method of a list will do this for you. If you want to guarantee order, sort the list first using sorted()
. Sorted accepts a cmp or key parameter to dictate how the sorting will happen:
a = [5, 4, 3]
print sorted(a).index(5)
Or:
a = ['one', 'aardvark', 'a']
print sorted(a, key=len).index('a')
I found this by adapting some tutos. Thanks to google, and to all of you ;)
def findall(L, test):
i=0
indices = []
while(True):
try:
# next value in list passing the test
nextvalue = filter(test, L[i:])[0]
# add index of this value in the index list,
# by searching the value in L[i:]
indices.append(L.index(nextvalue, i))
# iterate i, that is the next index from where to search
i=indices[-1]+1
#when there is no further "good value", filter returns [],
# hence there is an out of range exeption
except IndexError:
return indices
A very simple use:
a = [0,0,2,1]
ind = findall(a, lambda x:x>0))
[2, 3]
P.S. scuse my english
how's this one?
def global_index(lst, test):
return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )
Usage:
>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]
-
3Get pythonic: def global_index(lst, test): return (idx for idx, val in enumerate(lst) if test(val) )recursive– recursive2009年03月03日 04:01:48 +00:00Commented Mar 3, 2009 at 4:01
-
6filter(lambda x: x>3, [1,2,3,4,5,6])John Fouhy– John Fouhy2009年03月03日 21:15:22 +00:00Commented Mar 3, 2009 at 21:15