Python: Get Indices of List Elements According to Filter Condition

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)
# 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)
# 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])
# yields [0, 2, 3, 4]

About Gerhard Hagerer

I am a Computer Science Master. Talk to me!
This entry was posted in Computer Pragmatics and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s