Generate a list of tuples containing even and odd numbers from 1 to 10


This Python code creates a list called even_odd_pairs using a list comprehension to generate pairs of consecutive numbers where one is even and the other is odd. Here's how the code works:

  • even_odd_pairs = [(x, x + 1) for x in range(1, 11, 2)]: This line of code initializes a variable named even_odd_pairs and assigns it the result of a list comprehension.
    • for x in range(1, 11, 2): This part sets up a loop that iterates through odd numbers from 1 to 10 (inclusive) with a step size of 2. It generates values for x.
    • (x, x + 1): For each odd number x, this expression creates a tuple containing two elements: the original odd number x and the next consecutive number x + 1.
    • [(x, x + 1) for x in range(1, 11, 2)]: This is the list comprehension itself. It iterates through the odd numbers in the specified range (1 to 10) and pairs each odd number with its consecutive even number, including these pairs (tuples) in the new list.
  • print(even_odd_pairs): This line of code prints the even_odd_pairs list to the console.

Source Code

even_odd_pairs = [(x, x + 1) for x in range(1, 11, 2)]
print(even_odd_pairs)

Output

[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

Example Programs