By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,667 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

How to make arrays from Lists

P: n/a
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]] ?

gordc
Nov 12 '08 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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
Nov 12 '08 #2

P: n/a
On Nov 11, 7:48*pm, bearophileH...@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.
gordc
Nov 12 '08 #3

P: n/a
gc*******@yahoo.ca wrote:
On Nov 11, 7:48 pm, bearophileH...@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

Nov 12 '08 #4

P: n/a
En Tue, 11 Nov 2008 23:09:25 -0200, <gc*******@yahoo.caescribió:
On Nov 11, 7:48*pm, bearophileH...@lycos.com wrote:
>To create a 2D list, that is a list of lists:
x = [[0] * ncols for i in nrows]

Many thanks, I don't think I would ever 'discovered' this.
Try reading the FAQ:
http://www.python.org/doc/faq/progra...mensional-list

--
Gabriel Genellina

Nov 15 '08 #5

This discussion thread is closed

Replies have been disabled for this discussion.