4
def myFunction(name):
    index = 0
    list = self.getList()
    index = (x => x.name == name)
    return index

i want to use lamba expression to find an index of an element in a python list just as in C#. is it possible to use lambda expressions just as in C# to find an index of a specific element in python list . If so please provide an example

2
  • Is your list a standard python list or an object? Commented Nov 18, 2011 at 6:38
  • Can you please provide a more complete example of what you want to do, with sample input and output? Commented Nov 18, 2011 at 6:40

3 Answers 3

3

I think this code is closer to what you are asking for:

def indexMatching(seq, condition):
    for i,x in enumerate(seq):
        if condition(x):
            return i
    return -1

class Z(object):
    def __init__(self, name):
        self.name = name

class X(object):
    def __init__(self, zs):
        self.mylist = list(zs)

    def indexByName(self, name):
        return indexMatching(self.mylist, lambda x: x.name==name)

x = X([Z('Fred'), Z('Barney'), Z('Wilma'), Z('Betty')])

print x.indexByName('Wilma')

Returns 2.

The key idea is to use enumerate to maintain an index value while iterating over the sequence. enumerate(seq) returns a series of (index,item) pairs. Then when you find a matching item, return the index.

Sign up to request clarification or add additional context in comments.

Comments

3

If you really want to use a lambda, the syntax is:

lambda param, list: return_value

For example, this is a lamdba that does addition:

lambda x, y: x + y

I'm not sure how this could make your function easier to write though, since this is the most obvious way:

def myFunction(name):
    for i, x in enumerate(self.getList()):
        if x.name == name:
            return i

Your lamdba would be this though:

lamdba x: x.name == name

So one horrible way of doing this is:

def myFunction(name):
    matches = [index
               for index, value in enumerate(self.getList())
               if value.name == name]
    if matches:
        return matches[0]

1 Comment

Not quite what the OP asked for, despite the checkmark. Question didn't ask for match where the element in the list matched name, but where the element's name attribute (x.name) matches name. Your lambda would be lambda x: x.name == name. And he doesn't want x, he wants the index of x in the list.
0

Perhaps you can do:

idx = [i for i, a in enumerate(lst) if a.name == name][0]

1 Comment

And there are no such element? It will throw index out of bound exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.