Search code examples
python-3.xlistelement

Python: A constant subtract by elements of a list to return a list


I have a list decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8] and I want a list such that

new_position = 2 - decay_positions

Essentially I want a new list where its elements are equal to 2 subtracted by elements of decay_positions However when I do:

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
print(2 - decay_positions)

I get

TypeError: unsupported operand type(s) for -: 'int' and 'list'

So I thought maybe if dimensions aren't the same u can subtract. So I did

decay_positions = [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]
print([2]*len(decay_positions) - decay_positions)

but it still gives TypeError: unsupported operand type(s) for -: 'int' and 'list'

despite the fact that [2]*len(decay_positions) and decay_positions have the same size. So thoughts? Shouldn't element-wise subtraction be quite straightforward?


Solution

  • Use numpy ftw:

    >>> import numpy as np
    >>> decay_positions = np.array([0.2, 3, 0.5, 5, 1, 7, 1.5, 8])
    >>> 2 - decay_positions
    array([ 1.8, -1. ,  1.5, -3. ,  1. , -5. ,  0.5, -6. ])
    

    If you for some reason despise numpy, you could always use list comprehensions as a secondary option:

    >>> [2-dp for dp in [0.2, 3, 0.5, 5, 1, 7, 1.5, 8]]
    [1.8, -1, 1.5, -3, 1, -5, 0.5, -6]