Tuple of odd numbers from 1 to 20 in Python


This Python code creates a tuple called odds, which contains all the odd numbers from 1 to 20. Here's how the code works:

  • odds = tuple(x for x in range(1, 21) if x % 2 != 0): This line of code initializes a variable named odds and assigns it a tuple created using a generator expression.
    • for x in range(1, 21): This part of the code sets up a loop that iterates through each number x in the range from 1 to 20 (inclusive).
    • if x % 2 != 0: For each number, it checks if it is not divisible by 2 (i.e., an odd number) using the condition x % 2 != 0.
    • x: If a number is odd, it includes it in the generator expression.
    • tuple(...): This surrounds the generator expression and converts the generated odd numbers into a tuple.
  • print(odds): This line of code prints the odds tuple (which contains all the odd numbers from 1 to 20) to the console.

Source Code

odds = tuple(x for x in range(1, 21) if x % 2 != 0)
print(odds)

Output

(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)

Example Programs