Python: Filter a list of integers using Lambda
5. Integer Filter Lambda
Write a Python program to filter a list of integers using Lambda.
Sample Solution:
Python Code :
Sample Output:
Original list of integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Even numbers from the said list: [2, 4, 6, 8, 10] Odd numbers from the said list: [1, 3, 5, 7, 9]
Explanation:
In the exercise above -
- It initializes a list named 'nums' containing integers from 1 to 10.
- Prints the original list of integers ('nums') to the console.
- Filters even and odd numbers from the 'nums' list separately and prints them:
- It uses the "filter()" function with a lambda function to filter even numbers from the 'nums' list. The lambda function checks if the number is even (x % 2 == 0) and creates a new list called 'even_nums' containing only even numbers.
- It then prints the list of even numbers ('even_nums').
- Similarly, it uses the "filter()" function with a lambda function to filter odd numbers from the 'nums' list. The lambda function checks if the number is odd (x % 2 != 0) and creates a new list called 'odd_nums' containing only the odd numbers.
- It then prints the list of odd numbers ('odd_nums').
Test for a single number:
Python Code :
Sample Output:
Odd number Even number
For more Practice: Solve these Related Problems:
- Write a Python program to filter a list of integers, keeping only the prime numbers, using lambda.
- Write a Python program to filter a list of integers to keep only the perfect squares using lambda.
- Write a Python program to filter a list of integers to extract only Fibonacci numbers using lambda.
- Write a Python program to filter a list of integers to exclude numbers that are palindromic in their string representation using lambda.
Go to:
Previous: Write a Python program to sort a list of dictionaries using Lambda.
Next: Write a Python program to square and cube every number in a given list of integers using Lambda.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.