Create a list of numbers with their absolute values


This Python code takes a list of numbers, calculates their absolute values, and stores the absolute values in a new list called absolute_values. 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.
  • absolute_values = [abs(x) for x in numbers]: This line of code initializes a variable named absolute_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.
    • abs(x): For each number in the list, this expression calculates its absolute value using the abs() function. The abs() function returns the magnitude (positive value) of a number, effectively removing the negative sign if the number is negative.
    • [abs(x) for x in numbers]: This is the list comprehension itself. It iterates through the numbers in the numbers list and, for each number, calculates its absolute value and includes it in the new list.
  • print(numbers): This line of code prints the original numbers list to the console.
  • print(absolute_values): This line of code prints the absolute_values list to the console.

Source Code

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

Output

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

Example Programs