w3resource

Python function to filter even numbers

Python Filter: Exercise-1 with Solution

Write a Python function that filters out even numbers from a list of integers using the filter function.

Sample Solution:

Python Code:

def filter_even_nums(nums):
    """
    Filters out even nums from a list of integers.

    Args:
        nums (list): A list of integers.

    Returns:
        list: A new list containing only the odd numbers.
    """
    # Define the filtering function
    def is_odd(num):
        return num % 2 != 0

    # Use the filter function to filter out even numbers
    odd_nums = list(filter(is_odd, nums))

    return odd_nums

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original numbers:",nums)
result = filter_even_nums(nums)
print("After filters out even numbers from the said list of integers ")
print(result)  # Output: [1, 3, 5, 7, 9]

Explanation:

In the exercise above -

  • The "filter_even_numbers()" function takes a list of integers called numbers as input.
  • Inside the function, we define a nested function "is_odd()" that returns True for odd numbers (numbers not divisible by 2).
  • Next use the filter function to filter out even numbers from the numbers list by applying the is_odd function as the filtering condition.
  • The filtered odd numbers are converted to a list and returned as the result.

Sample Output:

Original numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After filters out even numbers from the said list of integers 
[1, 3, 5, 7, 9]

Flowchart:

Flowchart: Python function to filter even numbers

Python Code Editor:

Previous: Python Filter Exercise Home
Next: Python program to extract uppercase letters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/python-exercises/filter/python-filter-exercise-1.php