DEV Community

Cover image for Using Python list as a Stack
Ishaan Sheikh
Ishaan Sheikh

Posted on • Updated on

Using Python list as a Stack

What is a stack?

Stack is a data structure which 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 new element in the stack.

  2. Pop- To remove an element from the stack.

Using python list as stack

We can use the python's in-built list as 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]
Enter fullscreen mode Exit fullscreen mode

Pop

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

print(stack.pop()) # 6
Enter fullscreen mode Exit fullscreen mode

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

Getting top of stack

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

print(stack[-1]) # 5
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)