---
title: "Generate a list of all even, odd and prime numbers up to n in python with explanation"  
description: "Generate a list of all even, odd and prime numbers up to n in python with explanation"  
author: "Anubhav Sharma"  
published: 2025-04-23  
updated: 2025-04-27  
canonical: https://www.mindstick.com/forum/161532/generate-a-list-of-all-even-odd-and-prime-numbers-up-to-n-in-python-with-explanation  
category: "python"  
tags: ["python-3.4", "python"]  
reading_time: 2 minutes  

---

# Generate a list of all even, odd and prime numbers up to n in python with explanation

Using list comprehension.

## Replies

### Reply by Khushi Singh

## Explanation

**Even numbers** are those divisible by 2, like 2, 4, 6, 8, etc.

**Odd numbers** are those that are not divisible by 2, like 1, 3, 5, 7, etc.

**Prime numbers** are those greater than 1 that are divisible only by 1 and themselves, like 2, 3, 5, 7, 11, etc.

**Code Example:**\

```python
def generate_numbers(n):
   even_numbers = []
   odd_numbers = []
   prime_numbers = []

   for num in range(1, n + 1):
       # Check if number is even or odd
       if num % 2 == 0:
           even_numbers.append(num)
       else:
           odd_numbers.append(num)

       # Check if number is prime
       if num > 1:
           is_prime = True
           for i in range(2, int(num ** 0.5) + 1):
               if num % i == 0:
                   is_prime = False
                   break
           if is_prime:
               prime_numbers.append(num)
   return even_numbers, odd_numbers, prime_numbers
# Example usage
n = 20
evens, odds, primes = generate_numbers(n)

print("Even numbers:", evens)
print("Odd numbers:", odds)
print("Prime numbers:", primes)
```

## What the code does:

**For even numbers**, it checks if the number is divisible by 2 (`num % 2 == 0`).

**For odd numbers**, it adds those numbers that are not divisible by 2.

**For prime numbers**, it checks if a number is divisible by any number other than 1 and itself. It only checks up to the square root of the number for efficiency.

**Output for** `n = 20`**:**

**Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]**\
**Odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]**\
**Prime numbers: [2, 3, 5, 7, 11, 13, 17, 19]**

\
This code provides a simple way to categorize numbers as even, odd, and prime up to a given number `n`.\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\
\


---

Original Source: https://www.mindstick.com/forum/161532/generate-a-list-of-all-even-odd-and-prime-numbers-up-to-n-in-python-with-explanation

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
