Create a list of numbers with their reciprocal values


This Python code takes a list of numbers and creates a new list called reciprocal_values using a list comprehension. The new list contains the reciprocal (inverse) values of the numbers in the original list. Here's how the code works:

  • numbers = [2, 3, 4, 5, 6]: This line initializes a variable named numbers and assigns it a list containing five numbers.
  • reciprocal_values = [1/x for x in numbers]: This line of code initializes a variable named reciprocal_values and assigns it the result of a list comprehension.
    • for x in numbers: This part sets up a loop that iterates through each number x in the numbers list.
    • 1/x: For each number in the list, this expression calculates the reciprocal (inverse) value by dividing 1 by x.
    • [1/x for x in numbers]: This is the list comprehension itself. It iterates through the numbers in the numbers list, calculates the reciprocal value for each number, and includes these reciprocal values in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(reciprocal_values): This line of code prints the reciprocal_values list to the console.

Source Code

numbers = [2, 3, 4, 5, 6]
reciprocal_values = [1/x for x in numbers]
print(numbers)
print(reciprocal_values)

Output

[2, 3, 4, 5, 6]
[0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666]

Example Programs