TimGJ
TimGJ

Reputation: 1654

Returning the first item in a Python list which is contained in another list

Is there a Pythonic way of returning the first item in a list which is also an item in another list? At the moment I'm doing it using brute force and ignorance:

def FindFirstMatch(a, b):
    """
    Returns the first element in a for which there is a matching
    element in b or None if there is no match
    """

    for item in a:
        if item in b:
            return item
    return None

So FindFirstMatch(['Fred','Wilma','Barney','Betty'], ['Dino', 'Pebbles', 'Wilma', 'Bambam']) returns 'Wilma' but I wondered if there was a more elegant/efficient/Pythonic way.

Upvotes: 4

Views: 138

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90889

You can use a generator expression and 'next()' function . Example -

def FindFirstMatch(list1, list2):
    """
    Returns the first element in list "list1" for which there is a matching
    element in list "list2" or None if there is no match
    """

    setb = set(list2)

    return next((item for item in list1 if item in setb),None)

This would also return None if no such item meeting the condition exist in 'list2' .

In the above function, I am first converting list 'list2' into a set , so that searching in it can be done in constant time (otherwise searching in list is an O(n) time complexity operation).

Upvotes: 6

Related Questions