On Wed, Sep 23, 2009 at 1:14 PM, Rudolf <yellowblueyel...@gmail.com> wrote:
> Can someone tell me how to allocate single and multidimensional arrays
> in python. I looked online and it says to do the following x =
> ['1','2','3','4']
>
> However, I want a much larger array like a 100 elements, so I cant
> possibly do that. I want to allocate an array and then populate it
> using a for loop. Thanks for your help.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

In python they're called 'lists'.  There are C-style array objects but
you don't want to use them unless you specifically have to.

You can create an empty list like so:

x = []

and then put items into it with a for loop like so:

for item in some_iterable:
    x.append(item)

But in simple cases like this there's also the "list comprehension"
syntax which will do it all in one step:

x = [item for item in some_iterable]

But again in a case like this, if you're simply populating a list from
an iterable source you would just say:

x = list(some_iterable)

For multidimensional 'arrays' you just put lists in lists.  (Or use
NumPy if you really want arrays and are doing lots of wild processing
on them.)

But if you do this:

two_dimensional_list = [ [] for var in some_iterable]

The list of lists you create thereby will contain multiple references
to the /same/ inner list object.  This is something that catches many
people unawares.  You have to go back to using a for loop:

x = []
for n in range(100):
    x.append([(n, m) for m in range(10)])

(That will create a list of one hundred lists, each of which contains
ten tuples.)

Good luck.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to