Python stack iteration, best practice

What is the specific method for iterating the stack in python. is it best to use a for loop just like iterate over a list?

+4
source share
3 answers

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 
+1
source

If your stack can potentially grow to large sizes, you should not use List or your own stack class. Raymond Hettinger has already done the work for you and wrote the wonderful collections.deque . deque is a list, such as a data structure, that supports the addition of constant time and pops up at both ends.

 >>> from collections import deque >>> >>> stack = deque() >>> stack.append(1) >>> stack.append(2) >>> stack.append(3) >>> print stack deque([1,2,3]) 

Then, using deque.pop() and deque.popleft() , you can get 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 an efficient inverse iterator with memory.

+9
source

In Python, unlike other prog. languages ​​like C ++ (STL), we don’t have a predefined Stack data structure, we have a regular List .

So, if you want to iterate your "stack" as a regular list, you can just do something like:

 for item in reversed(my_list): # to preserve LIFO # do something with item # ... 

Now, if you want your list to behave like a stack (LIFO: Last In First Out), you could use the predefined list functions append and pop :

 >>> stack = [1, 2] >>> stack.append(3) >>> stack.append(4) >>> stack [1, 2, 3, 4] >>> stack.pop() 4 >>> stack [1, 2, 3] 

More on this at http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks

+3
source

Source: https://habr.com/ru/post/1380324/


All Articles