4

What I want to do is assign a nested list to another list. For example, from alist to blist.

alist = [[0], [1], [2], [3]]
blist = alist[:]
blist[0].append(1)

In this way, id(alist[0]) equals id(alist[1]), so alist also changes to [[0,1], [1], [2], [3]], that's not what I want.

The workaround I have is:

alist = [[0], [1], [2], [3]]
blist = []
for item in alist:
    blist.append(item[:])
blist[0].append(1)

In this workaround, alist won't be influenced by changing blist's items. However, it seems not so pythonic, is there any better resolution? That could resolve the deep copy of more the 2 level nested list. eg: alist = [[[1], 10], [[2], 20], [[3], 30]]

1
  • 1
    Your workaround can be written more simply as: blist = [item[:] for item in alist] or what I prefer [list(item) for item in alist]. However the solution by @cha0site is the proper way. Commented Jul 9, 2012 at 7:05

1 Answer 1

7

I think you want to use copy.deepcopy(), this also resolves deeper copies:

>>> import copy
>>> alist = [[0], [1], [2], [3]]
>>> blist = copy.deepcopy(alist)
>>> blist[0].append(1)
>>> alist
[[0], [1], [2], [3]]
>>> blist
[[0, 1], [1], [2], [3]]
Sign up to request clarification or add additional context in comments.

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.