How to make arrays from Lists
Robert Kern
robert.kern at gmail.com
Tue Nov 11 20:23:36 EST 2008
gc_ottawa at yahoo.ca wrote:
> On Nov 11, 7:48 pm, bearophileH... at lycos.com wrote:
>> gc_ott:
>>
>>> How do I change the value of any element to produce (say)
>>> [[99,0,0],[0,0,0],[0,0,0]] ?
>>> gordc
>> To create a 2D list, that is a list of lists:
>> x = [[0] * ncols for i in nrows]
>> (Don't do what you were doing, because you end with many references to
>> the same list, and that will give you troubles.)
>>
>> To set an item you do just:
>> x[0][0] = 99
>>
>> Bye,
>> bearophile
>
> Many thanks, I don't think I would ever 'discovered' this.
If you are trying to emulate numerical arrays, you may want to use numpy, instead.
http://numpy.scipy.org/
import numpy
x = numpy.zeros([3,3], dtype=int)
x[0,0] = 99
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list