Filter Odd Numbers from List

To filter odd numbers from List in Python, use filter() builtin function. Pass the function that returns True for an odd number, and the list of numbers, as arguments to filter() function.

Python filter() builtin function

In this tutorial, we will go through examples that filter odd numbers from list using filter() function.

Examples

Filter Odd Numbers from List

In this example, we take a list of integers and filter only odd values in it.

The function odd() takes a value and returns True if the value is odd, else it returns False.

Python Program

</>
Copy
def odd(x):
    return x % 2 == 1

a = [2, 5, 7, 8, 10, 13, 16]

result = filter(odd, a)
print('Original List :', a)
print('Filtered List :', list(result))

Output

Original List : [2, 5, 7, 8, 10, 13, 16]
Filtered List : [5, 7, 13]

Filter Odd Numbers with Lambda Function

We can also provide a lambda function for filter() that filters odd numbers.

Python Program

</>
Copy
a = [2, 5, 7, 8, 10, 13, 16]
result = filter(lambda x: x % 2 == 1, a)
print('Original List :', a)
print('Filtered List :', list(result))

Output

Original List : [2, 5, 7, 8, 10, 13, 16]
Filtered List : [5, 7, 13]

Conclusion

In this Python Tutorial, we learned how to filter odd numbers from list using filter() function.