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 to Split Lists in Python?
Lists in Python are a powerful and versatile data structure. In many situations, we might need to split a list into smaller sublists for various operations such as processing data in chunks, grouping items or creating multiple lists from a single source. Let's explore different methods to split list
3 min read
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
5 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 an
4 min read
How to Append Objects in a List in Python
The simplest way to append an object in a list using append() method. This method adds an object to the end of the list. Pythona = [1, 2, 3] #Using append method to add object at the end a.append(4) print(a) Output[1, 2, 3, 4] Let's look into various other methods to append object in any list are:Ta
2 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
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
How to iterate through a nested List in Python?
A nested list is a list that contains other lists. Working with nested lists can seem tricky at first but it becomes easy once we understand how to iterate through them. This is the easiest way to loop through a nested list. We can use a for loop to access each sublist in the main list, and then use
3 min read
Append Elements to Empty List in Python
In Python, lists are used to store multiple items in one variable. If we have an empty list and we want to add elements to it, we can do that in a few simple ways. The simplest way to add an item in empty list is by using the append() method. This method adds a single element to the end of the list.
2 min read
Sort a list in python
Sorting is a fundamental operation in programming, allowing you to arrange data in a specific order. Here is a code snippet to give you an idea about sorting.Python# Initializing a list a = [5, 1, 5, 6] # Sort modifies the given list a.sort() print(a) b = [5, 2, 9, 6] # Sorted does not modify the gi
5 min read
Python Program to Reverse the Content of a File using Stack
Given a file, the task is to change the content in reverse order using Stack, as well as store the lines of that file in reverse order in Python. Examples: Input: 1 2 3 4 5 Output: 5 4 3 2 1 Approach to Python Program to Reverse a Stack Using Recursion Create an empty stack. One by one push every l
2 min read