In Python, you can change every number in a list of numbers to its absolute value by calling the abs()
method on each element, for example, using list comprehension, like so:
numbers = [1234, -5678, 12.34, -56.78] abs_numbers = [abs(number) for number in numbers] print(abs_numbers) # [1234, 5678, 12.34, 56.78]
The code above would create a new list with all numbers in the list in absolute form. This is equivalent to the following, which uses map()
:
numbers = [1234, -5678, 12.34, -56.78] abs_numbers = list(map(lambda number: abs(number), numbers)) print(abs_numbers) # [1234, 5678, 12.34, 56.78]
However, using list comprehension provides a more readable and concise syntax. For that reason, it is generally preferred and would be the recommended way.
For completeness sake, you can also achieve the same result with a simple for..in
loop:
numbers = [1234, -5678, 12.34, -56.78] abs_numbers = [] for number in numbers: abs_numbers.append(abs(number)) print(abs_numbers) # [1234, 5678, 12.34, 56.78]
However, it might not be the best choice as it would create/overwrite a variable named "number
", which would persist even after the loop completes:
numbers = [1234, -5678, 12.34, -56.78] abs_numbers = [] for number in numbers: abs_numbers.append(abs(number)) print(number) # -56.78
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.