0

I'm trying to achieve something like C's structure, so I predefine a list :

__list = [0] * 1001

everything works well.

but when the list getting complicated (a sample):

__list = [{"name": '', "score": 0}] * 3

for item in __list:
    name, score = input("input name and score split with blank:\n").split()    # raw_input for python2
    item['name'] = name
    item['score'] = int(score)
print(__list)

and I input this:

Lily 23
Paul 12
James 28

out:

[{"name": "James", "score": 28}, {"name": "James", "score": 28}, {"name": "James", "score": 28}]

why?

Sinux
  • 1,728
  • 3
  • 15
  • 28

1 Answers1

2
__list = [{"name": '', "score": 0}] * 3

This will create a list with three references to a dictionary. Modifying any one of them modifies them all because they all refer to the same data.

If you want the list to hold references to different dictionaries, you may perform "deep copies" of a reference dict by using a list comprehension, for example,

__list = [{"name": '', "score": 0} for i in xrange(3)]
juanchopanza
  • 223,364
  • 34
  • 402
  • 480