Even numbers from 1 to 20 as tuples in Python


This Python code generates a tuple called evens using a generator expression. The tuple contains even numbers from 1 to 20. Here's how the code works:

  • evens = tuple(x for x in range(1, 21) if x % 2 == 0): This line of code initializes a variable named evens and assigns it a tuple created using a generator expression.
    • x for x in range(1, 21) if x % 2 == 0: This part of the code uses a generator expression to generate even numbers from 1 to 20.
      • for x in range(1, 21): This sets up a loop that iterates through numbers from 1 to 20 using the range(1, 21) iterable.
      • if x % 2 == 0: For each value of x in the range, it checks if x is even by evaluating x % 2 == 0, which is True for even numbers and False for odd numbers.
    • tuple(...): This surrounds the generator expression and converts the generated values (even numbers) into a tuple.
  • print(evens): This line of code prints the evens tuple to the console.

Source Code

evens = tuple(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