Append list in a loop [duplicate]

2019-06-11 05:40发布

This question already has an answer here:

I am missing something regarding append() in a for loop. I have two lists and I want to replace an item in list root = ['A', 'B', 'C', 'D'] say the first item index 0. The other list is replacements = [1, 2, 3, 4, 5, 6, 7, 8]

here's some code:

root = ['A', 'B', 'C', 'D']
replacements = [1, 2, 3, 4, 5, 6, 7, 8]
y = root.index('A')
new_list = []
for j in replacements:
    root[y]=j
    print root
    new_list.append(root)

but the output is messing with me and Python docs doesn't help. There must be something with my append function. as you can see I print root and the desired result occurs but when I look at new_list it repeats the last list eight times;

[1, 'B', 'C', 'D']
[2, 'B', 'C', 'D']
[3, 'B', 'C', 'D']
[4, 'B', 'C', 'D']
[5, 'B', 'C', 'D']
[6, 'B', 'C', 'D']
[7, 'B', 'C', 'D']
[8, 'B', 'C', 'D']

and new_list:

[[8, 'B', 'C', 'D'], [8, 'B', 'C', 'D'], [8, 'B', 'C', 'D'], 
[8, 'B', 'C', 'D'], [8, 'B', 'C', 'D'], [8, 'B', 'C', 'D'], 
[8, 'B', 'C', 'D'], [8, 'B', 'C', 'D']]

标签: python append
2条回答
姐就是有狂的资本
2楼-- · 2019-06-11 06:07

John1024 has a great solution, I just want to add one more solution here:

new_list = []
counter = 0
for j in replacements:
    root[y]=j
    new_list.append([])
    new_list[counter].extend(root)
    counter += 1

Hopefully this might be helpful for you

查看更多
Lonely孤独者°
3楼-- · 2019-06-11 06:21

Replace:

new_list.append(root)

With:

new_list.append(root[:])

The former appends to new_list a pointer to root. Each pointer points to the same data. Every time that root is updated, each element of new_list reflects that updated data.

The later appends to new_list a pointer to a copy of root. Each copy is independent. Changes to root do not affect copies of root that were made previously.

A simpler example

Compare this:

>>> root = ['A', 'B', 'C', 'D']
>>> b = root
>>> b[0] = 1
>>> root
[1, 'B', 'C', 'D']

With this:

>>> root = ['A', 'B', 'C', 'D']
>>> b = root[:]
>>> b[0] = 1
>>> root
['A', 'B', 'C', 'D']
查看更多
登录 后发表回答