List on python appending always the same value [duplicate]

A simplified example of your code currently to explain more fully why your results are the way they are:

all_items = []
new_item = {}
for i in range(0,5):
    new_item['a'] = i
    new_item['b'] = i

    all_items.append(new_item)
    print new_item
    print hex(id(new_item))  # print memory address of new_item

print all_items

Notice the memory address for your object is the same each time you go through your loop. This means that your object being added is the same, each time. So when you print the final list, you are printing the coordinates of the same object at every location in the loop.

Each time you go through the loop, the values are being updated – imagine you are painting over the same wall every day. The first day, it might be blue. The next day, you repaint the same wall (or object) and then it’s green. The last day you paint it orange and it’s orange – the same wall is always orange now. Your references to the attr object are like saying you have the same wall.

Even though you looked at the wall after painting it, the color changed. But afterwards it is a orange wall – even if you look at it 5 times.

When we make the object as a new object in each iteration, notice two things happen:

  1. the memory address changes
  2. the values persist as unique values

This is similar to painting different walls. After you finish painting the last one, each of the previous walls is still painted the color you first painted it.

You can see this in the following, where each object is created each iteration:

all_items = []
for i in range(0,5):
    new_item = {}
    new_item['a'] = i
    new_item['b'] = i

    all_items.append(new_item)
    print hex(id(new_item))


 print all_items

You can also do in a different way, such as:

all_items = []
for i in range(0,5):
    new_item = {'a': i, 'b': i}
    all_items.append(new_item)
    print hex(id(new_item))    
print all_items

or even in one step:

all_items = []
for i in range(0,5):
    all_items.append({'a': i, 'b': i})

print all_items

Either of the following will therefore work:

attr = {}
attr['height'] = height 
attr['weight'] = weight

men.append(attr)

or:

men.append({'height': height, 'weight': weight})

Leave a Comment