Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python implementing a function to find all elements in a list that meet a condition

Python implementing a function to find all elements in a list that meet a condition

Document Object Reference Manual Python3 Examples

We will write a Python function that takes a list and a condition function as parameters and returns all elements in the list that meet the condition. The condition function will be used to determine whether each element in the list satisfies a specific condition.

Example

def

find_elements

(

lst

,

condition

)

:

   

return

[

x

for

x

in

lst

if

condition

(

x

)

]

Example condition function

def

is_even

(

n

)

:

   

return

n %

2

==

0

Example list

numbers

=

[

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

,

10

]

Use the function to find all even numbers

even_numbers

=

find_elements

(

numbers

,

is_even

)

print

(

even_numbers

)

Code analysis:

  1. find_elements The function accepts two parameters:lst is the input list,condition is a function used to determine whether elements in the list satisfy the condition.
  2. Use a list comprehension [x for x in lst if condition(x)] to iterate over the list lst, and for each element x apply the condition function condition(x). If the condition is true, the element is included in the result list.
  3. is_even is an example condition function used to determine whether a number is even.
  4. numbers is an example list containing some integers.
  5. called find_elements function, passing numbers the list and is_even the condition function, finds all even numbers and stores them in even_numbers it.
  6. Finally, print even_numbers, outputting all the even numbers that meet the condition.

Output result:

[2, 4, 6, 8, 10]

Document Object Reference Manual Python3 Examples