A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-program-to-print-even-numbers-in-a-list/ below:

Print even numbers in a list - Python

Print even numbers in a list - Python

Last Updated : 11 Jul, 2025

Getting even numbers from a list in Python allows you to filter out all numbers that are divisible by 2. For example, given the list a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you might want to extract the even numbers [2, 4, 6, 8, 10]. There are various efficient methods to extract even numbers from a list. Let's explore different methods to do this efficiently.

Using List comprehension

List comprehensions is an efficient way to filter elements from a list. They are generally considered more Pythonic and faster than traditional loops.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

res = [val for val in a if val % 2 == 0]
print(res)

Explanation: [val for val in a if val % 2 == 0] iterates through the list a and selects only the even numbers.

Using filter()

filter() function provides a functional programming approach to filter elements from a list. It can be a bit less intuitive compared to list comprehensions, but it is still very useful.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

res = list(filter(lambda val: val % 2 == 0, a))
print(res)

Explanation: filter() function takes lambda function that tests each element in the list. lambda val: val % 2 == 0 returns True for even numbers, which are then included in the final list. We convert the result to a list using list().

Using loop

Using a traditional for loop is the most straightforward method, but it is generally less efficient and more verbose compared to other methods.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for val in a:
    if val % 2 == 0:
        print(val, end=" ")

Explanation: For loop iterates through each element in the list a. If the element is divisible by 2 (even number), it is printed.

Using Bitwise AND operator

This is a low-level, bitwise approach to check if a number is even. It works by performing a bitwise AND operation with 1, which will return 0 for even numbers and 1 for odd numbers.

Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

res = [val for val in a if val & 1 == 0]
print(res)

Explanation: expression val & 1 == 0 uses the bitwise AND operator to check if the least significant bit of a number is 0. Even numbers have their least significant bit as 0, so the condition evaluates to True for even numbers.

Related Articles

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4