On Apr 8, 3:21 pm, "M. Hamed" <mhels...@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)
??? The stack pointer is *always* at the end, except don't actually keep a real stack pointer, let list do it for you. Call append to push a value onto the end, and pop to pull it off. Or if you are really stuck on push/pop commands for a stack, do this: >>> class stack(list): ... push = list.append ... >>> ss = stack() >>> ss.push("x") >>> ss.push("Y") >>> ss ['x', 'Y'] >>> ss.pop() 'Y' >>> ss.pop() 'x' >>> ss.pop() Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop from empty list -- Paul -- http://mail.python.org/mailman/listinfo/python-list