Python: Check if a given function returns True for at least one element in the list
Python List: Exercise - 246 with Solution
Check Any True for Function
Write a Python program to check if a given function returns True for at least one element in the list.
Use any() in combination with map() to check if fn returns True for any element in the list.
Sample Solution:
Python Code:
# Define a function 'some' that takes a list 'lst' and an optional function 'fn'.
# It uses the 'any' function and 'map' to check if any element in the list satisfies the given condition specified by 'fn'.
def some(lst, fn=lambda x: x):
return any(map(fn, lst))
# Call the 'some' function with different lists and conditions, and print the results.
print(some([0, 1, 2, 0], lambda x: x >= 2))
print(some([5, 10, 20, 10], lambda x: x < 2))
Sample Output:
True False
Flowchart:
Python Code Editor:
Previous: Write a Python program to that takes any number of iterable objects or objects with a length property and returns the longest one.
Next: Write a Python program to calculate the difference between two iterables, without filtering duplicate values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-246.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics