You can negate all numbers in a Python list by using the unary minus operator (-
) on each element of the list, for example, using list comprehension, like so:
nums = [3, 2, -1, 0, 4, -6, -5] new_list = [-num for num in nums] print(new_list) # [-3, -2, 1, 0, -4, 6, 5]
The code above would create a new list with all numbers in the list negated (i.e. positive numbers will be flipped to negative and negative numbers will be converted to positive). This is equivalent to the following, using map()
:
nums = [3, 2, -1, 0, 4, -6, -5] new_list = list(map(lambda num: -num, nums)) print(new_list) # [-3, -2, 1, 0, -4, 6, 5]
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:
nums = [3, 2, -1, 0, 4, -6, -5] new_list = [] for num in nums: new_list.append(-num) print(new_list) # [-3, -2, 1, 0, -4, 6, 5]
However, it might not be the best choice as it would create/overwrite a variable named "num
", which would persist even after the loop completes:
nums = [3, 2, -1, 0, 4, -6, -5] new_list = [] for num in nums: new_list.append(-num) print(num) # -5
Hope you found this post useful. It was published . Please show your love and support by sharing this post.