How to make arrays from Lists

Benjamin Kaplan benjamin.kaplan at case.edu
Tue Nov 11 19:44:28 EST 2008


On Tue, Nov 11, 2008 at 7:32 PM, <gc_ottawa at yahoo.ca> wrote:

> I want to construct a 2-dimensional array from a List but I cannot
> find a simple way of changing any element. For example, construct a
> 3x3 array like this:-
> >>> x=[0,0,0]
>       x=[x]*3
> this produces [[0,0,0],[0,0,0],[0,0,0]. So far so good.
> How do I change the value of any element to produce (say)
> [[99,0,0],[0,0,0],[0,0,0]] ?
>

First of all, this is not a "2-d array". It is a list of lists. Each element
in x is a list consisting of three elements.
so x[0] is a list (x[0])[0] is the first element of that list. So what you
want is
>>>x[0][0] = 99

***In this case, each list inside of x refers to the same object. Any
changes you make to one row will appear in all of them.
>>> a = x[0]
>>> a
[0, 0, 0]
>>> a[0] = 99
>>> a
[99, 0, 0]
>>> x
[[99, 0, 0], [99, 0, 0], [99, 0, 0]]


> gordc
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081111/9fef7560/attachment-0001.html>


More information about the Python-list mailing list