Create a List of Even numbers from 1 to 20


This Python code creates a list called evens using a list comprehension, which contains even numbers from 1 to 20. Here's a breakdown of how the code works:

  • evens = [x for x in range(1, 21) if x % 2 == 0]: This line of code initializes a variable named evens and assigns it the result of a list comprehension.
    • for x in range(1, 21): This part sets up a loop that iterates through numbers from 1 to 20 (inclusive). The range(1, 21) function generates a sequence of numbers starting from 1 and ending at 20.
    • if x % 2 == 0: This is a condition that filters the numbers. It checks if the current value of x is even. The % operator calculates the remainder when x is divided by 2. If the remainder is 0, it means x is even.
    • [x for x in range(1, 21) if x % 2 == 0]: This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 20) and, for each number, checks if it's even. If the number is even, it includes it in the new list.
  • print(evens): This line of code prints the evens list to the console.

Source Code

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

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Example Programs