Python (without additional libraries or toolkits like numpy) is still lacking a convenient method to access indices of list elements according to a manually defined filter. We know this functionality from Matlab or numpy. This function makes these toolkits very practical for computations. So how to achieve that with pure Python without any libraries nor imports?

You could manually define a function therefore as lambda one liner (easy to copy&paste) or as comprehensive function definition, that can even handle dictionaries:

# lambda one liner
indices = lambda f, lst: [i for i,x in enumerate(lst) if f(x)]
# example
my_list = [1, 0, 3, 5, 1]
idx = indices(lambda x: x==1, my_list)
print(idx)
# yields [0, 4]
# function that can even handle dictionaries
def indices(lst, filtr=lambda x: bool(x)):
'''get list indices according to filter condition'''
if type(lst) == list:
return [i for i,x in enumerate(lst) if filtr(x)]
if type(lst) == dict:
return [i for i,x in lst.items() if filtr(x)]
raise TypeError('indices() only supports list and dict!')
# example
my_list = {'Hello': 1, 'fo': 0, 'ob': 3, 'ar': 5, 'World': 1}
idx = indices(my_list, lambda x: x==1)
print(idx)
# yields ['Hello', 'World']

I think the perfect way is making a list child class and adding the indices() function as class method. So, you can call it in an object oriented style ala list.indices():

class MyList(list):
def __init__(self, *args):
list.__init__(self, *args)
def indices(self, filtr=lambda x: bool(x)):
return [i for i,x in enumerate(self) if filtr(x)]
own_list = MyList([1,0,3,5,1])
own_list.indices()
# yields [0, 2, 3, 4]

### Like this:

Like Loading...

## About Gerhard Hagerer

I am a Computer Science Master. Talk to me!