2

At first, sorry if this is a really stupid question, but im a bloody python beginner and haven't found solution yet

I have given a list and have to subtract a certain value from each element of this list

my current approach is the following:

positions = [10, 45, 66, 110]
subtraction_value = 8

for x in range(len(positions)):                                   
    delta_distance = int(positions[x])-subtraction_value

I understand that I cant subtract a value from a list but i cant think of a way to update the position for every iteration

Hopefully the problem is somewhat understandable, english is unfortunately not my main language.

2 Answers2

1

You can just add a single line to the loop body that updates the actual list with the new value:

positions = [10, 45, 66, 110]
subtraction_value = 8

for x in range(len(positions)):                                   
    delta_distance = int(positions[x])-subtraction_value
    positions[x] = delta_distance

You can get the same result with the following comprehension:

positions = [x - subtraction_value for x in positions]
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

While the other answers are correct, there is also the option of using a map. This is especially good for when your calculations are "expensive" in terms of processing, and you want to delay them only until they are needed.

positions = map(lambda x: x - subtraction_value , positions)

Note that this doesn't create a list, map returns something like a generator that can be iterated on (and the calculations only happens then). To get back a list:

positions = list(map(lambda x: x - subtraction_value , positions))

Another option no one mentioned is using numpy:

import numpy as np
positions = [10, 45, 66, 110]
positions = np.array(positions) - subtraction_value 
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62