3

I wrote a code in python which looks like:

maplist=[{}]*11
mylist=[0]*11
maplist[0]['this']=1
print maplist

When I print maplist the output is :

[{'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}, {'this': 1}]

Expected is:

[{'this': 1}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

rather than only the first element of the list should have this key in the map. What is causing this problem?

1
  • It's amazing how often we get a subtle variation on the same question... in addition to marking things as duplicates, I'm starting to feel like we need to have a way to create a per-tag FAQ. Commented Jan 26, 2012 at 10:17

2 Answers 2

12

When you do the following:

maplist=[{}]*11

you end up with eleven references to the same dictionary. This means that when you modify one dictionary, they all appear to change.

To fix, replace that line with:

maplist=[{} for in xrange(11)]

Note that, since 0 is a scalar, the next line is fine as it is:

mylist=[0]*11
Sign up to request clarification or add additional context in comments.

2 Comments

Ohh came across this for the first time. Is there any specific reason why python do so , is it useful someehere?
@Piyush It is just a consequence of the way the * operator works on lists. See this answer for a more in-depth explanation.
3

The problem is when you type

maplist=[{}]*11

You're creating a list of 11 references to the same dict. Only one dictionary gets created.

To create 11 separate dictionaries you can do something like this:

>>> maplist = [{} for i in range(11)]
>>> maplist[0]['this'] = 1
>>> maplist
[{'this': 1}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.