Home > Back-end >  Outer list is cleared after clearing inner list
Outer list is cleared after clearing inner list

Time:01-31

In the following snippet, I append a list, x to another list u and the clear x. However, as you can see in the output, after clearing x, the second list, u is also cleared.

a = array([1,2,3,4])
x = []
u = []
for i in np.nditer(a):
    x.append(i.item())
u.append(x)
print("before x.clear(), u=", u)
x.clear()
print("after x.clear(), u=", u)

Output

before x.clear(), u= [[1, 2, 3, 4]]
after x.clear(), u= [[]]

What is the reason? I expect that by using append a copy of x is appended to u. How can I prevent u to be cleared after clearing x?

CodePudding user response:

Mark really answered this in the comments, but just for completeness, here's the working code using x.copy() doing what you asked for...

import numpy as np

a = np.array([1,2,3,4])
x = []
u = []
for i in np.nditer(a):
    x.append(i.item())
u.append(x.copy())
print("before x.clear(), u=", u)
x.clear()
print("after x.clear(), u=", u)

Output:

before x.clear(), u= [[1, 2, 3, 4]]
after x.clear(), u= [[1, 2, 3, 4]]

CodePudding user response:

I think you get it wrong. list.append() add an item to the end of the list. If you want to keep a copy of list and not affecting the copied one when you modified or deleted the original. You can do it several ways.

  1. u = x[:] or
  2. from copy import deepcopy
`u = deepcopy(x)`

See the documentation: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

  •  Tags:  
  • Related