Python program to print even numbers in a list
In this article, we’ll explore various methods to print even numbers from a list. The simplest approach is to use a loop for finding and printing the even numbers.
Using a Loop
We can simply use a loop (for loop) to find and print even numbers in a list.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Iterate through each element in the list
for val in a:
# Checks if a number is divisible by 2 (i.e., even).
if val % 2 == 0:
print(val, end = " ")
Output
2 4 6 8 10
Let us explore different methods to print even numbers in a list.
Using List Comprehension
List comprehensions provide a more concise way to filter elements from a list.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Create a list of even numbers using list comprehension
res = [val for val in a if val % 2 == 0]
print(res)
Output
[2, 4, 6, 8, 10]
Explanation: The list comprehension [val for val in a if val % 2 == 0] creates a new list containing only even numbers from the original list.
Using filter() Function
Python also provides an inbuilt function filter() that can be used for filtering a list based on a condition.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
res = list(filter(lambda val: val % 2 == 0, a))
print(res)
Output
[2, 4, 6, 8, 10]
Explanation:
- The filter() function filters elements of the list based on a provided function.
- The lambda function lambda val: val % 2 == 0 acts as the condition to filter out even numbers.
- We use list() to convert the filtered result back into a list.
Using Bitwise AND Operator
We can also use the bitwise AND operator (&) for checking if a number is even. This method works because even numbers always have their least significant bit set to 0 and if we take bitwise AND with 1 then the overall value would become 0.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
res = [val for val in a if val & 1 == 0]
print(res)
Output
[2, 4, 6, 8, 10]
Explanation:
- The condition val & 1 == 0 evaluates to True for even numbers because the binary representation of even numbers ends in 0.
- We use a list comprehension to collect all the even numbers from the list a and print the resulting list.