how to define the size of a list?

Alex Martelli aleax at aleax.it
Thu Nov 7 17:48:26 EST 2002


Marco Herrn wrote:

> Sorry if that is a stupid question, but I didn't find the answer in the
> docu. I want to define a matrix (a 2-dimensional list) with a specific
> size. But I didn't find a way to set the size of the list at creation
> time.
> 
> So how can I do this?

You can create a list of length N in many ways, such as:
    x = N * [0]
    x = [ 0 for i in range(N) ]
    x = range(N)
and so on, depending on what initial contents you want the
length-N list to have.

There are no "two-dimensional" lists in Python proper (and
you don't mention using the Numeric extension, which DOES
have them), so I think you mean a list of lists.  In this
case, take care NOT to use the first form for the outer level,
or that would give you a list containing N copies of the SAME
inner list -- surely not what you want.  I.e., to make a list
of N separate sublists, each sublist made up of N 0's, do:
    x = [ [0]*N for i in range(N) ]


Alex




More information about the Python-list mailing list