How to print even numbers in Python

Learn how to print even numbers in Python. Explore various methods, tips, real-world applications, and common debugging techniques.

How to print even numbers in Python
Published on: 
Wed
Mar 25, 2026
Updated on: 
Wed
Apr 1, 2026
The Replit Team

The ability to print even numbers in Python is a fundamental skill for data manipulation and flow control. Python's modulo operator, %, provides a straightforward method to identify these values.

In this article, you'll explore several techniques to accomplish this. You'll find practical tips, real-world applications, and advice to debug common errors, so you can select the right approach.

Using a basic for loop with if condition

for num in range(1, 11):
if num % 2 == 0:
print(num, end=" ")--OUTPUT--2 4 6 8 10

This approach combines a loop with a conditional statement to filter numbers. The for loop iterates through each number generated by range(1, 11), which includes integers from 1 to 10.

The core of this method is the if condition. It uses the modulo operator (%) to check if a number is divisible by two with no remainder. If the condition num % 2 == 0 is true, the number is even, and the print() function displays it. The end=" " argument ensures all printed numbers appear on the same line, separated by a space.

Basic approaches to print even numbers

While the for loop is effective, you can write more concise code using Python's range() step parameter, list comprehensions, or the filter() function.

Using range() with step parameter

for num in range(2, 11, 2):
print(num, end=" ")--OUTPUT--2 4 6 8 10

You can make the loop more efficient by using the optional third argument in the range() function—the step value. Setting the step to 2 tells the loop to increment by two with each iteration. This approach generates only even numbers from the start, removing the need for a conditional check.

  • Start: The sequence begins at 2.
  • Stop: It continues up to, but does not include, 11.
  • Step: The count increases by 2 each time.

Using list comprehension for even numbers

even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(even_numbers)--OUTPUT--[2, 4, 6, 8, 10]

List comprehensions offer a more compact, readable way to create lists from other iterables. This single line builds the even_numbers list by embedding a for loop and an if condition inside square brackets.

  • The expression starts with num, defining what each element in the new list will be.
  • The for num in range(1, 11) loop iterates through the numbers.
  • The if num % 2 == 0 clause filters the sequence, keeping only the even numbers.

The result is a new list containing only the values that satisfy the condition.

Using filter() function with lambda

even_numbers = list(filter(lambda x: x % 2 == 0, range(1, 11)))
print(even_numbers)--OUTPUT--[2, 4, 6, 8, 10]

The filter() function offers a functional programming approach. It applies a given function to each item in a sequence, keeping only the items for which the function returns True.

  • The lambda x: x % 2 == 0 is a concise, anonymous function that tests whether a number is even.
  • filter() runs this lambda on every number from range(1, 11).
  • The list() constructor then converts the filter object—which is an iterator—into a new list containing only the even numbers.

Advanced techniques for even numbers

While the basic approaches work well for simple scripts, you can turn to more specialized tools for greater efficiency and control in complex applications.

Using the itertools module

import itertools
evens = list(itertools.filterfalse(lambda x: x % 2, range(1, 11)))
print(evens)--OUTPUT--[2, 4, 6, 8, 10]

The itertools module offers tools for memory-efficient iteration, which is ideal for large datasets. Unlike the standard filter(), itertools.filterfalse() keeps items only when the condition evaluates to False.

  • The lambda function lambda x: x % 2 returns 0 for even numbers and 1 for odd numbers.
  • Because Python treats the number 0 as False, filterfalse() includes all the even numbers in its output.

This approach is a clever way to leverage Python's truthiness rules for a concise and performant solution.

Using numpy for efficient number sequences

import numpy as np
even_array = np.arange(2, 11, 2)
print(even_array)--OUTPUT--[2 4 6 8 10]

For heavy-duty numerical tasks, the NumPy library is a go-to solution. Its np.arange() function is a powerful alternative to Python's built-in range(), creating an array optimized for performance, which is ideal when you're working with large datasets.

  • Like range(), it accepts start, stop, and step arguments.
  • Setting the step to 2 generates only even numbers from the start.

This method returns a NumPy array—a specialized data structure that handles mathematical operations far more efficiently than standard Python lists.

Creating a custom even number generator with yield

def even_generator(start, end):
for num in range(start, end + 1):
if num % 2 == 0:
yield num

print(list(even_generator(1, 10)))--OUTPUT--[2, 4, 6, 8, 10]

For maximum control and memory efficiency, you can build a custom generator. The yield keyword transforms a regular function into a generator, which produces values on demand instead of storing them all in memory at once. This process is known as lazy evaluation.

  • The yield num statement pauses the function, returns the current even number, and saves its state.
  • When the next value is requested, the function resumes right where it left off.
  • This approach is ideal for processing large number ranges without creating a massive list upfront.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of just learning techniques, you can use Agent 4 to build complete applications directly from a description.

It helps you move from piecing together code to building a finished product. Agent 4 handles writing the code, connecting databases, managing APIs, and even deployment. You could build practical tools like:

  • A data validation tool that scans a list of user IDs and isolates the even-numbered ones for A/B testing.
  • A batch processing script that renames a series of files, assigning even numbers only to high-priority documents.
  • An inventory utility that filters product codes to display only items stocked on even-numbered shelves.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with simple methods, you might run into a few common pitfalls when filtering for even numbers.

Fixing common mistakes with range() step values

When using the step parameter in range(), a common mistake is starting the sequence with an odd number. This will generate only odd numbers, completely missing your target.

  • Incorrect Start: If you write range(1, 11, 2), the output will be 1, 3, 5, 7, 9.
  • Correct Start: To get even numbers, always begin your range with an even integer, like range(2, 11, 2).

Another frequent issue is the off-by-one error with the stop value. Remember that range() stops before the specified end number, so to include 10 in your sequence, you must set the stop value to 11.

Troubleshooting list comprehension with if conditions

With list comprehensions, the logic inside your if condition is critical. A simple typo can flip your results, causing you to collect odd numbers instead of even ones.

  • Check Your Logic: Always ensure your condition is if num % 2 == 0. Using == 1 will give you the opposite of what you want.
  • Don't Forget the Filter: It's also easy to forget the if clause altogether, which results in a list of all numbers from the range, not just the even ones.

Handling non-integer data with isinstance() checks

Your code might crash if the data you're iterating through contains non-integer values, such as strings or floats. Applying the modulo operator (%) to these types will raise a TypeError.

To prevent this, you can add a type check. By using the isinstance() function, you can confirm an item is an integer before you try to check if it's even. This makes your code more robust and prevents unexpected errors when dealing with mixed data types.

Fixing common mistakes with range() step values

The step parameter in range() is powerful, but your starting point is critical. If you begin with an odd number and step by two, you'll unintentionally generate only odd numbers. Examine the code below to see this common error in action.

for num in range(1, 11, 2):
print(num, end=" ")

The loop starts at 1 and jumps by 2, so it only ever lands on odd numbers. Check the corrected snippet below to see how a simple change gets the right result.

for num in range(2, 11, 2):
print(num, end=" ")

When using range() with a step of 2, your starting number determines the entire sequence. If you begin at 1, the loop will only ever produce odd numbers. To generate even numbers correctly, you must start the sequence with an even integer, such as 2. This simple adjustment ensures the loop iterates exclusively through even values. It's a common logic error to watch for when you need to generate specific numerical patterns.

Troubleshooting list comprehension with if conditions

The conciseness of list comprehensions can be a double-edged sword. A small logic error in the if clause is easy to miss. Forgetting the explicit comparison == 0 can lead to unexpected behavior due to Python's truthiness rules. Examine the code below.

even_numbers = [num for num in range(1, 11) if num % 2]
print(even_numbers)

The if num % 2 condition keeps numbers where the remainder is non-zero. Because Python treats 0 as False, this code unintentionally collects odd numbers instead of even ones. The corrected snippet below clarifies the proper logic.

even_numbers = [num for num in range(1, 11) if num % 2 == 0]
print(even_numbers)

By adding the explicit comparison == 0, the condition if num % 2 == 0 now correctly evaluates to True only for even numbers. This avoids the ambiguity of Python's truthiness rules, where a remainder of 0 would otherwise be treated as False. Always double-check your filter logic in list comprehensions to ensure you’re not accidentally inverting the results, especially when a zero value signifies a successful match.

Handling non-integer data with isinstance() checks

Applying the modulo operator (%) to non-integer data, like a string, will crash your script with a TypeError. This often happens when you're working with lists containing mixed data types. The code below demonstrates this exact scenario.

mixed_data = [1, 2, "3", 4, "5", 6]
even_numbers = [x for x in mixed_data if x % 2 == 0]
print(even_numbers)

The comprehension processes each item, but the % operator can't handle the string "3". This mismatch stops the code cold. Check the snippet below to see how you can safely filter mixed data types.

mixed_data = [1, 2, "3", 4, "5", 6]
even_numbers = [x for x in mixed_data if isinstance(x, int) and x % 2 == 0]
print(even_numbers)

The corrected code avoids a TypeError by first checking if an item is an integer with isinstance(x, int). Only after confirming the type does it apply the modulo operator (%). This two-step condition makes your code resilient, especially when processing mixed data from files or APIs. It ensures your list comprehension filters out non-integers gracefully instead of halting with an error, which is a common issue when working with real-world data.

Real-world applications

The same modulo logic you've learned is key for practical applications, from analyzing text to validating data integrity.

Finding words with even character count using len() and %

You can apply this same modulo logic to text, using the len() function to get a word's length and the % operator to check if it's even.

words = ["python", "code", "programming", "algorithm", "data"]
even_length_words = [word for word in words if len(word) % 2 == 0]
print(even_length_words)

This code uses a list comprehension, a concise and Pythonic way to create a new list. It builds even_length_words by filtering the original words list based on a condition.

  • The code iterates through each word in the list.
  • The if len(word) % 2 == 0 clause keeps only the words that satisfy the condition, effectively filtering out any with an odd character count.

The result is a new list containing just "python", "code", and "data", while the original words list remains unchanged.

Using even/odd parity for data validation with bin() and count()

The same even/odd logic is also fundamental to data validation, where parity checking uses the bin() and count() functions to verify the integrity of binary data.

# Simple data validation using even parity check
data = [0b1101, 0b1010, 0b1000, 0b1111]
for byte in data:
count_of_ones = bin(byte).count('1')
parity_bit = 0 if count_of_ones % 2 == 0 else 1
print(f"Data: {bin(byte)[2:]:>4}, Parity bit: {parity_bit}")

This script calculates a parity bit for each binary number in the data list, a common technique for detecting errors in data transmission. The code loops through each value, converting it into a binary string representation with the bin() function.

  • The count('1') method tallies the number of set bits—the ones—in each binary string.
  • A conditional expression then checks if this count is even using the modulo operator (%).
  • For an even count, the parity_bit is set to 0; otherwise, it's 1. This ensures the total number of ones, including the parity bit, is always even.

Get started with Replit

Now, turn these concepts into a real tool. Give Replit Agent a prompt like, “Build a utility that filters a CSV for even-numbered product IDs” or “Create a script that finds words with an even character count.”

Replit Agent will write the code, test for errors, and deploy your application. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.