Appending to a list in Python: adds last element every time?
Asked Answered
P

3

7

I want to append a dict to a list, but the result I'm getting isn't what I want.

My code:

records=[]
record={}
for i in range(0,2):
  record['a']=i  
  for j in range (0,2):
    record['b']=j
    records.append(record)
print records 

I expected:

[{'a': 0, 'b': 0}, {'a': 0, 'b': 1}, {'a': 1, 'b': 0}, {'a': 1, 'b': 1}]

I get instead:

[{'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}, {'a': 1, 'b': 1}]

Why is it only adding the last element every time?

Pearle answered 17/8, 2015 at 19:4 Comment(0)
C
13

You are reusing and adding one single dictionary. If you wanted separate dictionaries, either append a copy each time:

records = []
record = {}
for i in range(2):
    record['a'] = i  
    for j in range(2):
        record['b'] = j
        records.append(record.copy())

Or create a new dictionary each time:

records = []
for i in range(2):
    for j in range(2):
        record = {'a': i, 'b': j}
        records.append(record)

The latter approach lends itself to translation to a list comprehension:

records = [{'a': i, 'b': j} for i in range(2) for j in range(2)]
Cameo answered 17/8, 2015 at 19:6 Comment(0)
P
1

record.copy() will not work if you've nested dictionary, since it returns shallow copy. Use deepcopy instead which is full proof.

from copy import deepcopy
records.append(deepcopy(record))
Piny answered 9/8, 2021 at 14:22 Comment(0)
G
0

I faced this issue and records.append(deepcopy(record)) worked fine

Grandaunt answered 26/12, 2023 at 6:24 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.