Dynamically growing an array to implement a stack

Patrick Maupin pmaupin at gmail.com
Thu Apr 8 16:29:09 EDT 2010


On Apr 8, 3:21 pm, "M. Hamed" <mhels... at hotmail.com> wrote:
> I have trouble with some Python concept. The fact that you can not
> assign to a non-existent index in an array. For example:
>
> a = [0,1]
> a[2] =========> Generates an error
>
> I can use a.append(2) but that always appends to the end. Sometimes I
> want to use this array as a stack and hence my indexing logic would be
> something like:
>
> If you are already at the end (based on your stack pointer):
>       use append() then index (and inc your pointer)
> if not:
>       index directly (and inc your stack pointer)
>
> If feel that doing this everytime I want to add an element that I have
> to check whether it exists or not is too much. Is there any simpler
> way to do this?
>
> I know I can do something like this:
>
> a = numpy.zeros(MAX_STACK_SIZE)
>
> but I don't want to predetermine the stack size.
>
> Any help?
>
> Thanks

Well, if you never want to add intermediate data between your new
element and the stack, you can just do:

stack[index:index + 1] = [newelement]

Regards,
Pat



More information about the Python-list mailing list