Home » Python » Python programs

Using List as Stack in Python

Python | Using List as Stack: Here, we are going to learn how to use Lists as Stacks in Python? Here, we are implementing stack program by using list.
Submitted by IncludeHelp, on September 22, 2018

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

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]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.