0

I've got a sort of array in python, and i'm looking to subtract one from each int in all of it. for example:

arr = [[2,3,4],
      [5,6,7],
      [8,9,10]]
 #this should become this:
arr = [[1,2,3],
      [4,5,6],
      [7,8,9]]

there's a few ways i've tried to do this

for i in arr:
    for j in i:
        j-=1     #doesn't work!

I'm aware it would be easier to do this with numpy, but this is for a large project that i'm working on, so implementing numpy would take hours, if not more. Thanks!

3 Answers 3

2

You could use a nested list comprehension:

arr = [[y - 1 for y in x] for x in arr]
Sign up to request clarification or add additional context in comments.

Comments

1

So the way that you are doing it is just reassigning the variable j within your loop to one less its original value. However, what you want to do is reassign the value of the array AT the index j to one less its original value. To do this without using numpy, simply loop through all the indexes of the array, and then replace the value:

for i in range(len(arr)):
   for j in range(len(arr[i])):
      arr[i][j] -= 1

If you're unsure of why this is, look into how variable assignment works in Python.

Comments

0

Your solution didn't work, because jis a copy of the value from your array, rather than a pointer to the array item itself.

Below is sample code that works. Essentially, iterate through each location in the array, and modify the original array at that location.

arr = [[2,3,4],
      [5,6,7],
      [8,9,10]]
for x_idx, x in enumerate(arr):
    for y_idx, y in enumerate(x):
        arr[x_idx][y_idx] -= 1
print(arr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.