1

I have a numpy array A = np.array([1,2,3]). I want to add 1 to each element of this array, and return an array with each addition, separately:

My desired output would be:

list1 = [[2,2,3][1,3,3][1,2,4]]

I have tried the np.ufunc method to add my arrays, and using a normal list but both methods add the arrays/lists cumulatively:

In[1]:    list1 = []
          A = np.array([1,2,3])
          for i in range(len(A)):
              np.add.at(A, [i,], 1)
              list1.append(A)
              print(list1)

Out[1]:   [array([2, 2, 3])]
          [array([2, 3, 3]), array([2, 3, 3])]
          [array([2, 3, 4]), array([2, 3, 4]), array([2, 3, 4])]

This seems like something that needs to be done outside the for loop, but I'm not sure what. Where am I going wrong?

4
  • Can you clarify what you need help with? I'm not quite sure I understand what's going wrong... Commented Apr 19, 2021 at 12:30
  • I want to take the array [1,2,3] and add 1 to every index of this array and store them, separately in a new list. So I want list 1 = [[2,2,3],[1,3,3],[1,2,4]]. But I am getting list1 = [[2,3,4],[2,3,4],[2,3,4]] instead, where the arrays are added each time Commented Apr 19, 2021 at 12:32
  • 1
    Oh, ok. You're appending it into a new list. Have you tried printing A directly instead of appending it to a list and printing the list? Commented Apr 19, 2021 at 12:33
  • You said "return an array", then called it list1, showed something invalid, now say "in a new list". Can you make up your mind? Commented Apr 19, 2021 at 12:36

2 Answers 2

3
>>> A + np.eye(A.size)
array([[2., 2., 3.],
       [1., 3., 3.],
       [1., 2., 4.]])
Sign up to request clarification or add additional context in comments.

Comments

1

Loop through the list.

a = [1,2,3]
out = []
for c, n in enumerate(a):
    newlst = []
    for c2, v in enumerate(a):
        if not c2 == c:
            newlst.append(v)
        else:
            newlst.append(v+1)
    out.append(newlst)
print(out)

Output:

[[2, 2, 3], [1, 3, 3], [1, 2, 4]]

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.