[Baypiggies] One and two dim arrays in Python

Chris Rebert cvrebert at gmail.com
Tue Aug 26 02:06:05 CEST 2008

Your attempt doesn't work because you can't assign to indices of an
empty list (which is of length/size 0). You would need to instead use
.append() to add items on to the end of the list, e.g.:

a = []
for i in xrange(list_size):

And just to clarify, Python doesn't have any sort of declaration. You
can use Python's handy list comprehension syntax to abbreviate the
previous code as:

a = [something for i in xrange(list_size)]

Or it your placeholder values are immutable (e.g. numbers), you can
use the simpler shortcut:

a = [something] * list_size

For multidimensional lists, you need to be a bit careful. The pattern
(for a 2D list) is:

a = [[something for y in xrange(dimension_y_size) ] for x in

and you can continue the pattern in the obvious way for higher
dimensional lists.
Note that you can still use the aforementioned shortcut for the
innermost list when constructing multidimensional ones, again assuming
the placeholder value is immutable.

Hope that clears things up.

- Chris
Follow the path of the Iguana...
Rebertia: http://rebertia.com
Blog: http://blog.rebertia.com

On Mon, Aug 25, 2008 at 4:49 PM, David Elsen <elsen.david08 at gmail.com> wrote:
> Hi all,
> I would like to do something like following in Python:
> for i in range(0,10):
>      a[i] = something
> just to initialize some values for 1d array.
> I am getting the error message 'a' is not defined.
> Is there a way to declare 1d or 2d arrays in Python?
> Thanks,
> David
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies

More information about the Baypiggies mailing list