HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

Find matches in a list or dictionary

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
findmatchespythonlistdictionary

Problem

To find the value of the first element in the given list that satisfies the provided testing function, you can use a list comprehension and next() to return the first element in lst for which fn returns True.
To find the value of the last element in the given list that satisfies the provided testing function, you will use the same technique as above, but you'll use the [::-1] slice to reverse the list before iterating over it.
To find the index of the first element in the given list that satisfies the provided testing function, you will modify the original function to use enumerate().
To find the index of the last element in the given list that satisfies the provided testing function, you will modify the original function to use enumerate() and the [::-1] slice.
To find the indexes of all elements in the given list that satisfy the provided testing function, you will use enumerate() and a list comprehension to return the indexes of all elements in lst for which fn returns True.

Solution

def find(lst, fn):
  return next(x for x in lst if fn(x))

find([1, 2, 3, 4], lambda n: n % 2 == 1) # 1


To find the index of the first element in the given list that satisfies the provided testing function, you will modify the original function to use enumerate().
To find the index of the last element in the given list that satisfies the provided testing function, you will modify the original function to use enumerate() and the [::-1] slice.
To find the indexes of all elements in the given list that satisfy the provided testing function, you will use enumerate() and a list comprehension to return the indexes of all elements in lst for which fn returns True.
To find the key in the provided dictionary that has the given value, you will use dictionary.items() and next() to return the first key that has a value equal to val.
To find all keys in the provided dictionary that have the given value, you will use dictionary.items(), a generator and list() to return all keys that have a value equal to val.

Code Snippets

def find(lst, fn):
  return next(x for x in lst if fn(x))

find([1, 2, 3, 4], lambda n: n % 2 == 1) # 1
def find_last(lst, fn):
  return next(x for x in lst[::-1] if fn(x))

find_last([1, 2, 3, 4], lambda n: n % 2 == 1) # 3
def find_index(lst, fn):
  return next(i for i, x in enumerate(lst) if fn(x))

find_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 0

Context

From 30-seconds-of-code: find-matches-list-dictionary

Revisions (0)

No revisions yet.