Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

stack
python
push
pop

How to implement stack in Python

Educative Answers Team

A stack is a last-in-first-out (LIFO) data structure. It has three primitive operations:

  • Push: Add an element to the stack
  • Pop: Remove an element from the stack
  • Peek: Get the topmost element of the stack
svg viewer
stack

In Python, a stack is implemented using a list object.

  • To push an item in the stack, use the list function append list.append(item)
  • To pop an item in the stack, use the list function pop list.pop()
  • To get the top most item in the stack, write list[-1]

The following illustration explains the concept:

1 of 6

Example

The following code explains how to implement a stack in python:

list=[]
list.append(1) # append 1
print("push:",list)
list.append(2) # append 2
print("push:",list)
list.append(3) # append 3
print("push:",list)
list.pop() # pop 3
print("pop:",list)
print("peek:",list[-1]) # get top most element
list.pop() # pop 2
print("pop:",list)
print("peek:",list[-1]) # get top most element

RELATED TAGS

stack
python
push
pop
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring