Generate a list of numbers with their signs reversed


This Python code takes a list of numbers, negates each number (changes its sign to the opposite), and stores the negated numbers in a new list called opposite_signs. Here's how the code works:

  • numbers = [-2, 3, -5, 7, -11]: This line initializes a variable named numbers and assigns it a list containing five numbers, some of which are negative.
  • opposite_signs = [-x for x in numbers]: This line of code initializes a variable named opposite_signs 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.
    • -x: For each number in the list, this expression negates it by putting a minus sign in front of it. This effectively changes the sign of each number to the opposite.
    • [-x for x in numbers]: This is the list comprehension itself. It iterates through the numbers in the numbers list and, for each number, negates it and includes the negated number in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(opposite_signs): This line of code prints the opposite_signs list to the console.

Source Code

numbers = [-2, 3, -5, 7, -11]
opposite_signs = [-x for x in numbers]
print(numbers)
print(opposite_signs)

Output

[-2, 3, -5, 7, -11]
[2, -3, 5, -7, 11]

Example Programs