What is the specific method to iterate a stack in python. is the best practice to use a for loop just like to iterate a list?
If your stack can potentially grow to large proportions, you should absolutely not be using a List
or a custom stack class. Raymond Hettinger has already done the work for you and written the wonderful collections.deque
. The deque
is a list like data structure that supports constant time appends and pops from both ends.
>>> from collections import deque
>>>
>>> stack = deque()
>>> stack.append(1)
>>> stack.append(2)
>>> stack.append(3)
>>> print stack
deque([1,2,3])
By then appropriately using deque.pop()
and deque.popleft()
you can acheive both FILO and FIFO respectively. You can also iterate over it with for item in stack
if you want FIFO or for item in reversed(stack)
for FILO, which will generate a memory efficient reverse iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With