Search code examples
pythonlistdigital-signature

How to give the inverse of every number in a Python list


Is there any way in Python to give the opposite of each numeral element of a list in one line, without doing, for example:

for i in range(len(L)):
    L[i] = -L[i]

Considering the following list:

[0, 1, 2, 3..., 9]

The output should be

[0, -1, -2, -3..., -9]

Every number of the list should be its additive opposite.


-L obviously doesn't work.

I searched but I found only how to reverse a list, and not how to invert its elements (meaning that every number should become its additive inverse).


I know about list comprehensions, but I was wondering if there was a special keyword in Python to achieve this, or to do it in a cleaner way.


Solution

  • If your input values are numeric, you can do something like this

    negated_values=map(lambda x:-x, mylist)
    

    where

    print(list(negated_values))
    

    returns

    [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]