Wednesday, 21 January 2009

Python Gotcha

Spent ages last night trying to track down a bug in Python. I wanted to do something you don’t often need to do in Python – initialise a two-dimensional list – which I did like this ...
>>> a = [[None] * 4] * 2
>>> a
[[None, None, None, None], [None, None, None, None]]
Turns out I should have used a list comprehension to do it ...
>>> a = [[None] * 4 for i in range(2)]
>>> a
[[None, None, None, None], [None, None, None, None]]
They both look the same, but they are not! It’s fairly obvious when you think about it, but trying to track this down in a reasonably complex piece of code wasn’t easy ...