Alex.Zhang
Alex.Zhang

Reputation: 307

Nested python list assignment

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

Upvotes: 4

Views: 568

Answers (1)

cha0site
cha0site

Reputation: 10717

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

Upvotes: 7

Related Questions