This question already has an answer here:
- How to clone or copy a list? 15 answers
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']]