How to Create a List of Even Numbers in Python?

Estimated read time 1 min read

To create a list of even numbers in Python, you can use the built-in range() function and a list comprehension. Here’s an example code that creates a list of even numbers from 2 to 20:

even_numbers = [x for x in range(2, 21) if x % 2 == 0]
print(even_numbers)

In this example, we use the range() function to generate a sequence of numbers from 2 to 20 (inclusive), and then we use a list comprehension to create a new list that contains only the even numbers from that sequence. The if x % 2 == 0 condition checks if the number x is even, and only adds it to the list if it is. Finally, we print the list of even numbers using the print() function.

Note that we start the range() function from 2, since 1 is not an even number. Also, the upper limit of the range() function is 21, since the second argument is exclusive, meaning it generates numbers up to (but not including) 21.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply