![]() |
In Python list is one of the most widely used and popular built-in datatypes that represents ordered and mutable collections of elements. List also allows to storage of duplicate items. Lists are widely used for various tasks in Python programming, such as storing collections of data, implementing stacks and queues, and handling sequences of values. Using List As Stack In PythonStack is a linear data structure that follows the LIFO principle which means Last in First Out. In the stack insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack. Basic Operations on Stack:
Below are some of the examples by which we can use the list as a stack in Python: Push Operation Using List in PythonIn this operation, we push data to the stack which is implemented by a list. As we all know stack data structure follows the LIFO principle i.e., Last in First Out. Python3
Output
The Stack items are : 1 2 3 Pop Operation Using List in PythonThe pop Operation in stack use to remove the last element from the stack. Here, we will use pop() function to perform pop operation in list. If the stack is empty it return none. Python3
Output
Initial Stack [1, 2, 3] Popped Element: 3 Top Operation Using List in PythonThe top() method of stack used to print the topmost element of the stack. It return the last or recently pushed element from the last. Python3
Output
Top Element of Stack is : 3 isEmpty() Operation Using List in PythonThe isEmpty method of stack used to check the stack is empty or not. If the stack is empty it return 1 else it returns 0. Python3
Output
0 Creating a Class and Implementing Stack MethodIn this example, we will implement a stack class and we will implement all the stack opertion like push, pop, top, empty, and size by the help of class method. Python
Output
['Lokesh', 'Diwakar', 'Aniket', 'Ritik'] 4 ('Removed element from the st : ', 'Ritik') ('Top element in the stack : ', 'Aniket') 0 ['Lokesh', 'Diwakar', 'Aniket', 'Vimal Kant'] |
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |