Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Stack Iteration, best practices

Tags:

python

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?

like image 677
Gayan Kalanamith Avatar asked Dec 07 '22 18:12

Gayan Kalanamith


1 Answers

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.

like image 51
Endophage Avatar answered Dec 30 '22 04:12

Endophage