w3resource

Python: Find the value of the last element in the given list that satisfies the provided testing function


Last Value Satisfying Function

Write a Python program to find the value of the last element in the given list that satisfies the provided testing function.

Use a list comprehension and next() to return the last element in lst for which fn returns True.

Sample Solution:

Python Code:

# Define a function 'find_last' that takes a list 'lst' and a function 'fn' as input.
def find_last(lst, fn):
    # Use a generator expression to find the last element 'x' in the reversed list 'lst[::-1]'
    # for which 'fn(x)' is true. The 'next' function is used to retrieve the last matching element.
    return next(x for x in lst[::-1] if fn(x))

# Call the 'find_last' function with a list and a lambda function to find the last odd number in the list.
# Print the result.
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 1))
# Call the 'find_last' function again with a lambda function to find the last even number in the list.
# Print the result.
print(find_last([1, 2, 3, 4], lambda n: n % 2 == 0))

Sample Output:

3
4

Flowchart:

Flowchart: Find the value of the last element in the given list that satisfies the provided testing function.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the last value in a list that satisfies a given predicate, returning a default value if none qualify.
  • Write a Python program to retrieve the last even number in a list using a provided testing function.
  • Write a Python program to find the last value in a list that meets a condition defined by a lambda function and output its index along with the value.
  • Write a Python program to determine the last value in a list that, when processed by a function, results in a number greater than a specified threshold.

Python Code Editor:

Previous: Write a Python program to find the value of the first element in the given list that satisfies the provided testing function.
Next: Write a Python program to create a dictionary with the unique values of a given list as keys and their frequencies as the values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.