Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 840
Kike .Asekas Avatar asked Dec 15 '22 12:12

Kike .Asekas


2 Answers

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)]
like image 110
Martijn Pieters Avatar answered Feb 24 '23 03:02

Martijn Pieters


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))
like image 33
SCode Avatar answered Feb 24 '23 03:02

SCode