Stacks in Python

KoshurAI
2 min readDec 26, 2022

--

A stack is a linear data structure that follows the last-in, first-out (LIFO) principle, meaning that the element that was added last to the stack will be the first one to be removed. In Python, you can implement a stack using a list or a collections.deque object.

Here’s an example of how to implement a stack using a list:

stack = []

# Push an element onto the stack
stack.append(1)
stack.append(2)
stack.append(3)

# Pop an element from the stack
print(stack.pop()) # prints 3
print(stack.pop()) # prints 2
print(stack.pop()) # prints 1

Here’s an example of how to implement a stack using a collections.deque object:

from collections import deque

stack = deque()

# Push an element onto the stack
stack.append(1)
stack.append(2)
stack.append(3)

# Pop an element from the stack
print(stack.pop()) # prints 3
print(stack.pop()) # prints 2
print(stack.pop()) # prints 1

In both examples, the append() method is used to push an element onto the stack, and the pop() method is used to pop an element from the stack.

Note that the pop() method raises an IndexError if the stack is empty, so you may want to check if the stack is empty before calling pop(). You can do this using the len() function or the bool() function, like this:

if len(stack) > 0:
element = stack.pop()

# or

if stack:
element = stack.pop()

You can also use the peek() method to get the top element of the stack without removing it. In the list implementation, you can use the [-1] index to do this:

top_element = stack[-1]

In the collections.deque implementation, you can use the popleft() method with a parameter of None:

top_element = stack.popleft(None)

This will return the top element of the stack without removing it.

--

--

KoshurAI
KoshurAI

Written by KoshurAI

Passionate about Data Science? I offer personalized data science training and mentorship. Join my course today to unlock your true potential in Data Science.

No responses yet