creating a matrix in python?

Carsten Geckeler uioziaremwpl at spammotel.com
Mon Jun 25 14:55:02 EDT 2001


On Sat, 23 Jun 2001, Adonis wrote:

> how do i go about this?
>
> i have looked into the tutorial 100+ times and cant get anything on
> matrices out of it?
> only thing i came up with was some thing like:
> blah = ['buh', 'blah', 'wassah']
> blah[1][0]
> 'buh'

bla[1][0] should return 'b'.  bla[1] is the second item in the list, i.e.
'blah', and 'blah'[0] returns the first item of 'blah'.

> any help would greatly be appreciated.

You are probably interested in numeric matrices which can be expressed as
lists of lists.  Let's have a look a the following interactive session.

>>> mat = [[1,2,3], [4,5,6], [7,8,9]]
>>> mat
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> mat[0]
[1, 2, 3]
>>> mat[1]
[4, 5, 6]
>>> mat[1][2]
6
>>> mat[2][1] = 999
>>> mat[0][2] = -999
>>> mat
[[1, 2, -999], [4, 5, 6], [7, 999, 9]]

Building such matrices in pograms may be a little bit more complicated as
you can't assign values directly into a non-existing matrix (like in
Perl).

>>> newmatrix[2][0] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: There is no variable named 'newmatrix'

As one solution you may build an empty matrix (filled with 0 or None) and
enter the elements later, like here:

>>> mat2 = []
>>> for i in range(3):
...     mat2.append([0]*3)
...
>>> mat2
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> mat2[2][0] = 999
>>> mat2
[[0, 0, 0], [0, 0, 0], [999, 0, 0]]

There are surely better ways of doing the above, but I think you get an
impression how lists of lists work.

Cheers, Carsten
-- 
Carsten Geckeler





More information about the Python-list mailing list