Filtering Out Even Numbers

Write a Python lambda function that filters out even numbers from a list. Return the list of odd numbers.

Example 1:

Input: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output: [1, 3, 5, 7, 9]

Example 2:

Input: [10, 15, 20, 25, 30]

Output: [15, 25]

Use the filter() function with a lambda function to select only the odd numbers.

# Define the lambda function
filter_odds = lambda nums: list(filter(lambda x: x % 2 != 0, nums))

# Test the function
print(filter_odds([1, 2, 3, 4, 5, 6, 7, 8, 9])) # Output: [1, 3, 5, 7, 9]
print(filter_odds([10, 15, 20, 25, 30])) # Output: [15, 25]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!