Q:

Using List as Stack in Python

belongs to collection: Python List Programs

0

First of all, we must aware with the Stack - the stack is a linear data structure that works on LIFO mechanism i.e. Last In First Out (that means Last inserted item will be removed (popped) first).

Thus, to implement a stack, basically we have to do two things:

  1. Inserting (PUSH) elements at the end of the list
  2. Removing (POP) elements from the end of the list

i.e. both operations should be done from one end.

In Python, we can implement a stack by using list methods as they have the capability to insert or remove/pop elements from the end of the list.

Method that will be used:

  1. append(x) : Appends x at the end of the list
  2. pop() : Removes last elements of the list

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to use list stack

# Python Example: use list as stack 

# Declare a list named as "stack"
stack = [10, 20, 30]
print ("stack elements: ");
print (stack)

# push operation 
stack.append(40)
stack.append(50)
print ("Stack elements after push opration...");
print (stack)

# push operation 
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print (stack.pop (), " is removed/popped...")
print ("Stack elements after pop operation...");
print (stack)

Output

stack elements:
[10, 20, 30]
Stack elements after push opration...
[10, 20, 30, 40, 50]
50  is removed/popped...
40  is removed/popped...
30  is removed/popped...
Stack elements after pop operation...
[10, 20]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Extend a list using + Operator... >>
<< Python | Convert a string to integers list...