1

I want to know how I can add a value to each element of a NXN multidimensional array. I tried [x+1 for x in multiArray], but this one yields only for a 1D array.

Maybe something like this:

multiArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

addingArray=[]
for i in range(3):
    for j in range(3):
        addingArray.append(multiArray[j]+1) #(adding 1 to each element here)  

But this seems to be wrong?

2 Answers 2

1

You're getting 1D array as result because you have addingArray as a simple list. So, you iterate over all the elements in your multiArray and add 1 to it and you're appending the result to a list.


For efficiency reasons, it is advisable to use NumPy for arrays. Then, you can simply use broadcasting to add value to each element of the array. Below is an illustration:

# input array
In [180]: multiArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 

# add 1 to each value of the array
In [181]: multiArray + 1  
Out[181]: 
array([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]])

If you indeed want a plain python list as the result for some reasons, you can simply cast it to one:

In [182]: (multiArray + 1).tolist()  
Out[182]: [[2, 3, 4], [5, 6, 7], [8, 9, 10]]
Sign up to request clarification or add additional context in comments.

Comments

0

Indice-iteration

You need to have a inner list to get the inner results, and access the good value with multiArray[i][j], also don't use constant 3 take the habit to use object length

addingArray=[]
for i in range(len(multiArray)):
    innerArray = []
    for j in range(len(multiArray[i])):
        innerArray.append(multiArray[i][j]+1)
    addingArray.append(innerArray)  

print(addingArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Value iteration

You can also iterate over the arra directly to simplify and don't both with indices

addingArray=[]
for inner in multiArray:
    innerArray = []
    for value in inner:
        innerArray.append(value+1)
    addingArray.append(innerArray)  

List comprehension

And shorten it with list comprehension syntax

multiArray = [[v+1 for v in inner] for inner in multiArray]
print(multiArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.