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]]

jamylak
134k30 gold badges238 silver badges239 bronze badges
asked Jul 9, 2012 at 6:47
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]]
jamylak
134k30 gold badges238 silver badges239 bronze badges
answered Jul 9, 2012 at 6:51
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.