As others have said, python doesn't really have a built-in stack data type, but you can use a list to emulate.
When using a list as a stack, you can model the behavior of first-in-last-out with append () as push and pop () as pop, as julio.alegria describes.
If you want to use this list in a for-loop, but still it behaves in FILO mode, you can change the order of the elements using this slice syntax: [::-1] .
Example:
for element in stack[::-1]: print element
If you use a custom class that implements the stack, as long as it has certain methods __iter__() and next() , you can use it in understanding lists, for loops, etc.
This way you can implement a custom iterator that removes elements when iterating over it, just like with the corresponding stack.
Example:
class Stack: def __init__(self): self.data = [] def push(self,n): self.data.append(n) def pop(self): return self.data.pop() def __iter__(self): return self def next(self): if len(self.data)>0: return self.pop() else: raise StopIteration filo = Stack() filo.push(1) filo.push(2) filo.push(3) for i in filo: print i
source share