Data Structures in Python: Stack

The above figure is a good example of stack data structure in Python. Suppose stones arranged on top of each other are elements of stack now the last stone added is the topmost one and if we want to remove a stone we will remove the last one added that is from the top. So we can observe a pattern of Last In First Out(LIFO) i.e. the last element added is the first element retrieved. That‘s so simple.

We already read a data structure that can be used as a stack and guess which one? The answer is a List. Yes, because in the list using append we can add elements to the end, and using pop we can remove the element that was added last.

Let’s create a list:

Here we have a list named stack with some values init.

Adding Element

Using the append method we can add elements to the end:

Removing Element

Using the pop method we can remove the last element added:

That’s all for the stack. It’s so simple and easy to understand. I hope you understood properly if not I would say read it again especially the first paragraph.


Lecture 1:

Lecture 2:

Lecture 3:

Lecture 4:

Lecture 5:

Lecture 6:

Lecture 7:

Lecture 8:

Lecture 9:

Lecture 10:

Lecture 11:

Lecture 12:

Lecture 13:

Lecture 14:

Lecture 15:

Lecture 16:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store