How to implement list as stack in Python

Hello guys, in this tutorial we will learn how to implement a list as a stack in Python.

The list is a collection of objects of different data types. The list is a sequence of mutable objects like different details of a student(Name, Roll No., Age). Mutable objects are those which we can change later.

The stack is a linear data structure that follows the order of Last In First Out(LIFO). Stack uses two principal operations: push and pop. Push adds the element to the collection and pop remove the most recently added element from the collection.

Also read: How to find common elements from two tuples

Implementation of the list as a stack

Real-Life Example of stack

In a restaurant, the heap of plates is the best example of a stack. The plates that come on last added at the top and removed first which follows the order of LIFO.

Working of Stack

Let’s begin the topic with a decent example.

Declare a variable list that will contain the data of the list and print it.

list=[12,23,'Codespeedy','winter',23.5]
print(list)

Output:

[12, 23, 'Codespeedy', 'winter', 23.5]

Now add data in the list using append, that is a push operation. We can clearly see that newly inserted data is added at the end of the list.

list.append('Technology')
list.append('SEO')
print(list)

Output:

[12, 23, 'Codespeedy', 'winter', 23.5, 'Technology', 'SEO']

As we had learned earlier that stack uses two operations push and pop. Let’s perform the pop operation on the list.

print(list.pop())
print(list.pop())

Output:

SEO
Technology

In the output, we can see that the last two inserted objects which were “SEO” and “Technology” is removed from the list according to the order they were inserted. “SEO” was inserted at last and removed first.

Here is the whole program at a glance.

list=[12,23,'Codespeedy','winter',23.5]
print(list)
list.append('Technology')
list.append('SEO')
print(list)
print(list.pop())
print(list.pop())
print(list)

Output:

[12, 23, 'Codespeedy', 'winter', 23.5]
[12, 23, 'Codespeedy', 'winter', 23.5, 'Technology', 'SEO']
SEO
Technology
[12, 23, 'Codespeedy', 'winter', 23.5]

I hope you all understand the implementation of the stack using the list in Python.

 

Leave a Reply

Your email address will not be published. Required fields are marked *