Dynamically growing an array to implement a stack

M. Hamed mhelshou at hotmail.com
Thu Apr 8 16:54:28 EDT 2010


Thanks Patrick, that is what I was exactly looking for.

Paul, thanks for your example. wasn't familiar with the stack class. I
feel Patrick's method is a lot simpler for my purpose.

Regards.

On Apr 8, 1:29 pm, Patrick Maupin <pmau... at gmail.com> wrote:
> 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