Stack
Python
stack using list python
https://www.geeksforgeeks.org/stack-i...
Implementation
There are various ways from which a stack can be implemented in Python. This article covers the implementation of a stack using data structures and modules from the Python library.
Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Implementation using list:
Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order.
Unfortunately, the list has a few shortcomings. The biggest issue is that it can run into speed issues as it grows. The items in the list are stored next to each other in memory, if the stack grows bigger than the block of memory that currently holds it, then Python needs to do some memory allocations. This can lead to some append() calls taking much longer than other ones.
Python program to
demonstrate stack implementation
using list
stack = []
append() function to push
element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
pop() function to pop
element from stack in
LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
uncommenting print(stack.pop())
will cause an IndexError
as the stack is now empty
Output:
Initial stack
['a', 'b', 'c']
from collections import deque
stack = deque()
append() function to push
element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
pop() function to pop
element from stack in
LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
uncommenting print(stack.pop())
will cause an IndexError
as the stack is now empty
On this page of the site you can watch the video online Stack using list python with a duration of hours minute second in good quality, which was uploaded by the user Cloudvala 05 December 2017, share the link with friends and acquaintances, this video has already been watched 45 times on youtube and it was liked by 1 viewers. Enjoy your viewing!