### lessons in python

17 July 2008

I've been learning Python lately, and although I'm loath to say so, it's a pretty sweet language. I do miss my semicolons, but I'll learn to do without; it'll never replace Perl for text munging, but then what will?

That said, I ran into some semi-unexpected behaviour today, and haven't found much by way of documentation. Python has an excellent construct for building strings, arrays, what have you by way of multiplication. For example:

```>>> 'a'*3
'aaa'
>>> [1]*3
[1,1,1]
```

Sweet! I know it's old hat, and a crapton of other languages do it, but this is the first time I've gotten to use it in practice. It's epic for things like:

```>>> x = [0] * 20
```

Creating an all-0 array is a snap!

Of course, if everything was peachy-keen, there wouldn't be much point in this. As a math guy, 0'd-out arrays are fine, but 0'd-out multi-dimensional arrays are even better. Let's say I want a matrix of 0's:

```>>> x = [ [0] * 3 ] * 3
>>> x
[[0,0,0],[0,0,0],[0,0,0]]
```

Win! Alright, now I want to set the bottom-right corner to 1. Just because.

```>>> x[2][2] = 1
>>> x
[[0,0,1],[0,0,1],[0,0,1]]
```

What? Fail. I'll readily admit to not being a member of the Python dev project, so this is pure speculation, but here's the guess: the `*` operator works on values for fundamental types, including strings. For all other types, it operates on references. Thus constructing a 2d array as above, the first “row” is the same as the second is the same as the third, and updates barf the entire structure.

Until I find something better, it's time to go with the naive solution:

```>>> x = []
>>> for i in range(0,3):
...   x.append([0]*3)
...
>>> x[2][2] = 1
>>> x
[[0,0,0],[0,0,0],[0,0,1]]
```

Lesson learned. Drop suggestions if you have them!

All included graphics are generated at LaTeX to png .