Menu

1 / 2

How to use stacks in Python

DEV Community·Santiago Hernandez·6 months ago
#jysFBcHx
#using#datastructures#python#dsa#stack
Reading 0:00
15s threshold

A stack is a linear data structure where inserted elements are kept in insertion order and only the last one to be added is removed, this is also known as LIFO (last in first out) behavior.

A traditional Stack supports three operations:

Insertion or push

Peek or top

Deletion or pop

Execution times for both operations can vary slightly depending on the implementation, all three can be executed in constant times O(1) with the right data structure.

Examples

Consider the following list of numbers, let's assume the last element in the list is the last one to be inserted:

stack = [ 1 , 7 , 5 , 6 , 5 , 12 , 4 ]

Enter fullscreen mode

Exit fullscreen mode

The following operations will produce the following results and the list will behave like a stack:

stack = [ 1 , 7 , 5 , 6 , 5 , 12 , 4 ] stack .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.