Using list comprehension.
Generate a list of all even, odd and prime numbers up to n in python with explanation
278
23-Apr-2025
Updated on 27-Apr-2025
Khushi Singh
25-Apr-2025Explanation
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:
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.