How to Use Lists as Stacks and Queues in Python
Last Updated :
21 Jan, 2025
In Python, lists can be used to implement a variety of data structures, including stacks and queues. In this article, we’ll explore how to use Python lists to create and perform basic operations on stacks and queues.
Using List as Stack in Python
A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle. In simpler terms, the last element added to the stack is the first one to be removed. Think of it like a stack of plates, we can only take the top plate off the stack, and to add a new plate, we place it on top.
The basic operations associated with a stack include:
Operation | Description |
---|
Push | Adding an element to the top of the stack. |
---|
Pop | Removing the element from the top of the stack. |
---|
Peek (or Top) | Viewing the element at the top of the stack without removing it. |
---|
IsEmpty | Checking if the stack is empty. |
---|
Below are some of the examples by which we can understand using list as a stack in Python:
Push Operation
In this example, a stack is initialized as an empty list, and elements are successively added to the top of the stack using the append
method. The append
method ensures the last item is added at the end of the list, simulating the push operation of a stack.
Python
li = []
li.append(1)
li.append(100)
li.append(23493)
print(li)
Pop Operation
The pop method removes and returns the last element from the stack, thus following the LIFO principle. After performing the pop operation, the stack shrinks, and the remaining elements are printed.
Python
li = [1, 2, 4, 4, 100, 212]
# Pop the top element from the stack
a = li.pop()
# Display the popped element and updated stack
print(a)
print(li)
Output212
[1, 2, 4, 4, 100]
Top Operation
To view the top element without removing it, we can use negative indexing (-1
) in Python. This provides a quick way to access the last element of the list.
Python
li = [1, 2, 4, 54, 3, 3532, 23]
# Access the top element without popping
a =li[-1]
print(a)
IsEmpty Operation
To check whether the stack is empty, we can simply evaluate if the list has any elements. An empty list evaluates to False
, while a non-empty list evaluates to True
.
Python
# Initialize an empty stack
li = []
# Check if the stack is empty
if not li :
print("empty")
else:
print("not empty")
Using List as Queues
A queue is another essential data structure that follows the First In, First Out (FIFO) principle. In a queue, the first element added is the first one to be removed. Queues are commonly used in scenarios where tasks or processes are executed in the order they are received. Some common operations associated with queues include:
Operation | Description |
---|
Enqueue | Adding an element to the rear (end) of the queue. |
---|
Dequeue | Removing the element from the front (head) of the queue. |
---|
Front | Viewing the element at the front without removing it. |
---|
Rear | Viewing the element at the rear without removing it. |
---|
IsEmpty | Checking if the queue is empty. |
---|
Below are some of the examples by which we can understand about using list as queues in Python:
Enqueue Operation
In Python, we can define a simple Queue
class to simulate the enqueue operation. The enqueue
method appends elements to the end of the list, simulating the addition of items to the queue.
Python
# Initialize an empty queue
a = []
# Enqueue Operation (adding elements to the queue)
a.append(10)
a.append(20)
a.append(30)
print(a)
Dequeue Operation
dequeue
method removes and returns the first element from the queue. This operation simulates the behavior of a queue, where elements are processed in the order they arrive.
Python
# Initialize an empty queue
a = []
# removing the first element
if a: # Check if the queue is not empty
res = a.pop(0)
print(res)
else:
print("Empty")
Front and Rear Operation
To view the front or rear elements of the queue without removing them, we can simply access the first or last element of the list using indexing.
Python
# Initialize queue
a = [10, 20, 30]
# Front Operation
if a: # Check if the queue is not empty
res = a[0]
print(res)
else:
print("Empty")
# Rear Operation
if a: # Check if the queue is not empty
res = a[-1]
print(res)
else:
print("Empty")
IsEmpty Operation
In a queue, this operation helps determine if there are any elements available to process or if the queue is completely empty.
Python
# checking if the queue is empty
a=[10, 20, 30]
res = len(a) == 0
print(res)
Similar Reads
How Can Python Lists Transformed into other Data Structures
Python, a versatile and widely used programming language, provides a rich set of data structures to accommodate various programming needs. One of the fundamental data structures in Python is the list, a dynamic array that allows the storage of heterogeneous elements. While lists are powerful, there
4 min read
Python | Ways to sum list of lists and return sum list
When working with nested lists (lists of lists), we may need to compute the sum of corresponding elements across all inner lists. In this article, we will see how Python provides multiple methods to perform this task. The most common and efficient way to sum up a list of lists is by using zip() comb
2 min read
Python - Index Value repetition in List
Given a list of elements, The task is to write a Python program to repeat each index value as per the value in that index. Input : test_list = [3, 0, 4, 2] Output : [0, 0, 0, 2, 2, 2, 2, 3, 3] Explanation : 0 is repeated 3 times as its index value is 3. Input : test_list = [3, 4, 2] Output : [0, 0,
7 min read
How to Yield Values from List in Python
In Python, we often deal with large lists where processing all elements at once might be inefficient in terms of memory usage. The yield keyword allows us to create iterators that yield values one at a time, instead of storing them all in memory. In this article, we will explore different methods to
3 min read
Implementation of Stack in Python using List
Stack is a linear data structure that follows the LIFO principle which means Last in First Out. In the stack insertion of a new element and removal of an existing element takes place at the same end represented as the top of the stack. Basic Operations on Stack: push():- This is a method to insert a
4 min read
Sort Tuple of Lists in Python
The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
3 min read
Shift from Front to Rear in List - Python
The task of shifting the first element to the rear in a list in Python involves moving the first element of the list to the end while maintaining the order of the remaining elements. For example, given the list a = [1, 4, 5, 6, 7, 8, 9, 12], the goal is to produce [4, 5, 6, 7, 8, 9, 12, 1]. Using co
3 min read
Python Program to Implement Stack Using Linked List
In Python, creating a stack using a linked list involves implementing a data structure where elements are added and removed in a last-in-first-out (LIFO) manner. This approach uses the concept of nodes interconnected by pointers, allowing efficient insertion and deletion operations. We are given a L
4 min read
Python - Add list elements to tuples list
Sometimes, while working with Python tuples, we can have a problem in which we need to add all the elements of a particular list to all tuples of a list. This kind of problem can come in domains such as web development and day-day programming. Let's discuss certain ways in which this task can be don
6 min read
Python | Convert Lists to column tuples
Sometimes, while working with data, we can have a problem in which we need to get alike index elements in a single container. This means the columns of Matrix/Multiple lists need to be converted to list of tuples, each comprising of like index elements. Let's discuss certain ways in which this task
11 min read