Using Python list as a Stack

Ishaan Sheikh
1 min readOct 11, 2022

--

Stack of stones, Photo by Jeremy Thomas on Unsplash

What is a stack?

Stack is a data structure that follows the LIFO property, which means Last-In-First-Out. The element inserted last will be the first to be removed.

Stack operations

  1. Push- To insert a new element in the stack.
  2. Pop- To remove an element from the stack.

Using python list as stack

We can use python’s in-built list as a stack data structure.

Push

You can use the in-built append method to insert element at the end of the array/list.

stack = []
stack.append(3)
stack.append(4)
stack.append(5)
stack.append(6)
print(stack) # [3, 4, 5, 6]

Pop

To pop an element we can use the in-built pop method on list.

print(stack.pop()) # 6

This method will remove the last element in the list if we do not specify any element to be removed.

Getting the top of the stack

To get the top element in the stack we can use python’s in-built feature to index the list from the end.

print(stack[-1]) # 5

--

--

Ishaan Sheikh

Software Engineer💻, Quick learner. Twitter — @imishaan005 Website — https://frikishaan.com