Sunday, February 27, 2011

Python quirks

Saw for myself a funny quirk in Python (2.6).

Suppose you want to create a list of dictionaries, which will be populated later.

My first idea was to do this:
 >>> a = [{}]*3

At the first glance, it works. But just look at this:
>>> a[0]["bbb"]=1
>>> a
[{'bbb': 1}, {'bbb': 1}, {'bbb': 1}]

Not exactly what you would expect, heh.

The way to do it right seems to be more wordly:
>>> a=[]
>>> for i in range(3):
... a[i]={}
>>> a
[{}, {}, {}]
>>> a[1]["bbb"]=1
>>> a
[{}, {'bbb': 1}, {}]

By the way, initializing a list with None is not a problem:
>>> c = [None]*5

Nevertheless, this will not work:
>>> for e in c:
... e = {}
...
>>> c
[None, None, None, None, None]

This will:
>>> c[2]={}
>>> c[1]={}
>>> c[2]["aaa"]=3
>>> c[1]["bbb"]=4
>>> c
[None, {'bbb': 4}, {'aaa': 3}, None, None]
>>> c[1]["aaa"]=5
>>> c
[None, {'aaa': 5, 'bbb': 4}, {'aaa': 3}, None, None]

No comments:

Post a Comment