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:
stack = [1,2,3,4,5]
Here we have a list named stack with some values init.
Adding Element
Using the append method we can add elements to the end:
stack.append(6)
stack.append(7)print(stack)#OUTPUT
[1,2,3,4,5,6,7]
Removing Element
Using the pop method we can remove the last element added:
print(stack.pop())#OUTPUT
7
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.
Lectures
Lecture 1: https://medium.com/@saifmdco/data-structures-with-python-introduction-4dadeffa2215
Lecture 2: https://medium.com/@saifmdco/data-structures-with-python-arrays-c498518bf7fd
Lecture 3: https://medium.com/@saifmdco/data-structures-in-python-lists-653a3ad103ab
Lecture 4: https://medium.com/@saifmdco/data-structures-in-python-tuples-3c350640cd9a
Lecture 5: https://medium.com/@saifmdco/data-structures-in-python-dictionary-fad27ffdda8b
Lecture 6: https://medium.com/@saifmdco/data-structures-in-python-2d-array-6bc0154aa717
Lecture 7: https://medium.com/@saifmdco/data-structures-in-python-matrix-22adba5aa597
Lecture 8: https://medium.com/@saifmdco/data-structures-in-python-sets-92d5445e97e8
Lecture 9: https://medium.com/@saifmdco/data-structures-in-python-chainmap-fca2a9d47249
Lecture 10: https://medium.com/@saifmdco/data-structures-in-python-linkedlist-50f2118c659e
Lecture 11: https://medium.com/@saifmdco/data-structures-in-python-stack-6bf182d63581
Lecture 12: https://medium.com/@saifmdco/data-structures-in-python-queue-6361d3dcff0
Lecture 13: https://medium.com/@saifmdco/data-structures-in-python-dequeue-1a585e269a55
Lecture 14: https://medium.com/@saifmdco/data-structures-in-python-custom-stack-b7b9173b4eae
Lecture 15: https://medium.com/@saifmdco/data-structures-in-python-hash-table-39be784eefc1
Lecture 16: https://medium.com/@saifmdco/data-structures-in-python-doubly-linked-list-fe698d74756c