Data Structures in Python - Types and Examples (A Complete Guide)
Python Data Structures
Are you a novice in Python? Have you just started with Python? Python programming language can be used for anything. It's used for data analysis, scripting, software development, etc. Data structures are the building blocks of any programming language and so is Python. A data structure is storing and organizing data in the computer memory. It's a branch of Computer Science that deals with arranging such large datasets in such a manner so that they can be accessed and modified as per the requirements.
In this Python tutorial, we'll delve into the different data structures used in Python. If you're a beginner to Python, you must understand the data structures the language supports. So let's begin.
Read More: Top 50 Python Interview Questions and Answers |
Types of Data Structures in Python
Data Structures are mainly classified into two categories:
- Primitive Data Structures: They store the data of only one type. It is the basic way of representing data that contains simple values. Data types like integer, float, string, and booleans come in this category.
- Non-Primitive Data Structures: They don't just store a value, but rather a collection of values in various formats. They can store data of more than one type.
Non-primitive data structures can further be categorized into two categories:
- Built-In: Python offers implicit support for built-in structures that enable storing and accessing data e.g. lists, tuples, sets, and dictionaries.
- User-Defined: Python also provides the functionality to create your own data structures e.g. Stack, Tree, Queue, etc. so that you can have full control over their functionality.
Read More: Data Types in Python |
Let's now study the Non-Primitive Data Structures in detail.
Built-In Data Structures in Python
1. Python Lists
Lists store data of different data types sequentially. It is a mutable data type in Python i.e. its elements can be changed after creation. We can access the elements of a list using indexes starting from 0. It's represented using square brackets [] and elements inside it are separated by commas.
Example of List in Python
# Initializing a List
myList = ["ScholarHat", "Shailendra Chuauhan", "Girdhar Singh"]
# Display the list
print("A diverse Python list: ")
print(myList)
# Creating a Nested List
nestedList = [["Sakshi", "Sourav"], ["Pradnya", "Pragati"]]
print("\nNested List: ")
print(nestedList)
# Accessing elements from the list
print("\nAccessing elements from the list:")
print(myList[0])
print(myList[2])
# Accessing elements using negative indexing
print("\nAccessing elements with negative indexing:")
# Print the last element of the list
print(myList[-1])
# Print the second last element of the list
print(myList[-2])
The above program demonstrates the list and operations performed on it.
Output
A diverse Python list:
['ScholarHat', 'Shailendra Chuauhan', 'Girdhar Singh']
Nested List:
[['Sakshi', 'Sourav'], ['Pradnya', 'Pragati']]
Accessing elements from the list:
ScholarHat
Girdhar Singh
Accessing elements with negative indexing:
Girdhar Singh
Shailendra Chuauhan
Read More: Python Lists: List Methods and Operations |
2. Python Dictionary
A dictionary in Python is a group of key-value pairs. Every key is distinct and corresponds to a single value. It can be created using curly braces {} with key-value pairs separated by colons.
Example of a Dictionary in Python
# Creating a Dictionary with mixed keys
myDict = {'Course': 'Python', 34: ['Beginner', 'Advanced']}
print("Created Dictionary: ")
print(myDict)
# Accessing an element using its key
print("Accessing an element using its key:")
print(myDict['Course'])
# Accessing an element using the get() method
print("Accessing an element using get():")
print(myDict.get(34))
# Creating a dictionary using dictionary comprehension
squaredDict = {x: x**2 for x in range(1, 6)}
print("Dictionary comprehension example:")
print(squaredDict)
The above program demonstrates a dictionary and operations performed on it.
Output
Created Dictionary:
{'Course': 'Python', 34: ['Beginner', 'Advanced']}
Accessing an element using its key:
Python
Accessing an element using get():
['Beginner', 'Advanced']
Dictionary comprehension example:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Read More: Python Dictionaries (With Examples): A Comprehensive Tutorial |
3. Python Tuples
Tuples are ordered collections of elements, similar to Python lists, but they are immutable. This implies that once a tuple has been created, it cannot be altered. Tuples can be formed by listing a sequence of values separated by commas, with or without enclosing parentheses.
Example of a Tuple in Python
# Defining a Tuple with string elements
myTuple = ('Welcome', 'to', 'ScholarHat')
print("\nTuple with strings:")
print(myTuple)
# Converting a list to a Tuple
myList = [100, 200, 300, 400]
print("\nTuple created from a list:")
myTuple = tuple(myList)
# Accessing elements through indexing
print("Accessing the first element of the tuple:")
print(myTuple[0])
# Using negative indexing to access elements
print("\nAccessing the last element of the tuple using negative indexing:")
print(myTuple[-1])
The above program demonstrates a tuple and operations performed on it.
Output
print("\nAccessing the third last element of the tuple:")
print(myTuple[-3])
Read More: Tuples in Python with Examples |
4. Python Sets
Sets are an unordered collection of unique elements. These are enclosed in curly braces and are useful to create lists that only hold unique values in the dataset.
Example of a Set in Python
# Creating a Set of both string and numerical values
mySet = set([90, 'ScholarHat', 3.14, 'Shailendra Chauhan', 400, 'Sakshi'])
print("\nA Set with mixed value types:")
print(mySet)
# Iterating through the set using a for loop
print("\nIterating through the elements of the set:")
for item in mySet:
print(item, end=" ")
print()
# Membership testing using the 'in' keyword
print("'ScholarHat' present in the set:", 'ScholarHat' in mySet)
The above program demonstrates a set and operations performed on it.
Output
A Set with mixed value types:
{3.14, 'ScholarHat', 400, 'Shailendra Chauhan', 'Sakshi', 90}
Iterating through the elements of the set:
3.14 ScholarHat 400 Shailendra Chauhan Sakshi 90
'ScholarHat' present in the set: True
Python Frozen Sets
The frozenset class in Python implements an immutable version of the set that can’t be changed after it’s been constructed. The frozenset objects are static and allow only query operations on their elements, not insertions or deletions. As these objects are static and hashable, they can be used as dictionary keys or as elements of another set, which isn’t possible with regular set objects. To instantiate a frozenset, you need to provide an iterable as an argument to the frozenset() constructor.
Example of a Frozen Set in Python
# Creating a regular set
regular_set = set(["Sakshi", "Pragati", "Shobha"])
print("Regular Set:")
print(regular_set)
# Creating a frozenset
immutable_set = frozenset(["Sourav", "Shailendra", "Girdhar"])
print("\nFrozen Set:")
print(immutable_set)
The above program differentiates between regular and frozen sets. While you can freely modify a regular set, attempting to alter a frozenset, such as adding new elements, will result in an error, underscoring the immutable nature of frozensets.
Output
Regular Set:
{'Shobha', 'Sakshi', 'Pragati'}
Frozen Set:
frozenset({'Girdhar', 'Sourav', 'Shailendra'})
5. Python Bytearray
Python Bytearray gives a mutable sequence of integers in the range 0 <= x < 256. Unlike strings or tuples, bytearrays can be modified in place.
Example of a Bytearray in Python
# Initializing a bytearray
byte_seq = bytearray([50, 100, 150, 200])
print("Initial Bytearray:")
print(byte_seq)
# Accessing elements in bytearray
print("\nAccessing an Element:", byte_seq[3])
# Modifying elements in the bytearray
byte_seq[1] = 190
print("\nAfter Modification:")
print(byte_seq)
# Appending new elements to the bytearray
byte_seq.append(205)
print("\nAfter Appending an Element:")
print(byte_seq)
The above program demonstrates a bytearray and operations performed on it.
Output
Initial Bytearray:
bytearray(b'2d\x96\xc8')
Accessing an Element: 200
After Modification:
bytearray(b'2\xbe\x96\xc8')
After Appending an Element:
bytearray(b'2\xbe\x96\xc8\xcd')
Collection Module in Python
Collection Module is a built-in module that provides alternatives to Python's general-purpose built-in containers, like dict, list, set, and tuple. It encompasses a range of specialized container data types providing diverse alternatives to Python's native containers.
Read More: Modules in Python |
Let's look at some of the most commonly used containers within the collection module.
1. Counters
Counters are a subclass of dictionaries designed to count hashable objects. Counters are invaluable for tallying elements and implementing counting algorithms with precision and efficiency.
Example of Counters in Python
from collections import Counter
# Creating a counter
company = Counter(['ScholarHat', 'DotNetTricks', 'Sakshi', 'ScholarHat', 'DotNetTricks', 'Sakshi', 'ScholarHat'])
print("Company Counter:")
print(company)
# Updating the counter
company.update(['Sakshi', 'ScholarHat'])
print("\nAfter Updating:")
print(company)
# Accessing the most common elements
print("\nMost Common Elements:")
print(company.most_common(2))
The above program demonstrates a counter and its associated operations.
Output
Company Counter:
Counter({'ScholarHat': 3, 'DotNetTricks': 2, 'Sakshi': 2})
After Updating:
Counter({'ScholarHat': 4, 'Sakshi': 3, 'DotNetTricks': 2})
Most Common Elements:
[('ScholarHat', 4), ('Sakshi', 3)]
2. OrderedDict
An OrderedDict, a subclass of a dictionary, preserves the order of items as they're added, simplifying the insertion and deletion of elements.
Example of OrderedDict in Python
from collections import OrderedDict
# Creating an OrderedDict
ordered_dict = OrderedDict([('ScholarHat', 2), ('DotNetTricks', 3), ('Sakshi', 1)])
print("OrderedDict:")
print(ordered_dict)
# Adding an element
ordered_dict.update({'Sourav': 4})
print("\nAfter Adding an Element:")
print(ordered_dict)
# Reversing the order
reverse_ordered_dict = OrderedDict(reversed(list(ordered_dict.items())))
print("\nReversed OrderedDict:")
print(reverse_ordered_dict)
The above program demonstrates the OrderedDict and its associated operations.
Output
OrderedDict:
OrderedDict([('ScholarHat', 2), ('DotNetTricks', 3), ('Sakshi', 1)])
After Adding an Element:
OrderedDict([('ScholarHat', 2), ('DotNetTricks', 3), ('Sakshi', 1), ('Sourav', 4)])
Reversed OrderedDict:
OrderedDict([('Sourav', 4), ('Sakshi', 1), ('DotNetTricks', 3), ('ScholarHat', 2)])
3. DefaultDict
It is a dictionary subclass that calls a factory function to supply missing values, simplifying the handling of missing keys.
Example of OrderedDict in Python
from collections import defaultdict
# Creating a defaultdict
default_dict = defaultdict(int)
default_dict['ScholarHat'] = 1
default_dict['DotNetTricks'] += 3
print("DefaultDict:")
print(default_dict)
The above program demonstrates the creation of the DefaultDict.
Output
DefaultDict:
defaultdict(, {'ScholarHat': 1, 'DotNetTricks': 3})
4. ChainMap
A ChainMap groups multiple dictionaries into a single view, making it easy to manage multiple scopes.
Example of OrderedDict in Python
from collections import ChainMap
dict1 = {'ScholaHat': 3, 'Sakshi': 2}
dict2 = {'Sourav': 4, 'ScholaHat': 1}
chain_map = ChainMap(dict1, dict2)
print("ChainMap:")
print(chain_map)
The above program demonstrates the creation of the ChainMap.
Output
ChainMap:
ChainMap({'ScholaHat': 3, 'Sakshi': 2}, {'Sourav': 4, 'ScholaHat': 1})
5. NamedTuple
NamedTuples facilitate the creation of tuple-like objects that support indexing, iteration, and accessing fields using attribute lookup.
Example of NamedTuple in Python
from collections import namedtuple
# Creating a namedtuple
Employee = namedtuple('Employee', ['name', 'id'])
sakshi = Employee(name='Sakshi', id=5)
print("NamedTuple:")
print(sakshi.name, sakshi.id)
The above program demonstrates the creation of a NamedTuple.
Output
NamedTuple:
Sakshi 5
6. UserDict
UserDict is a wrapper around dictionary objects for easier dictionary subclassing.
Example of UserDict in Python
from collections import UserDict
# Creating a UserDict
user_dict = UserDict(ScholarHat=2, DotNetTricks=3)
print("UserDict:")
print(user_dict)
The above program demonstrates the creation of a UserDict.
Output
UserDict:
{'ScholarHat': 2, 'DotNetTricks': 3}
7. UserString
UserString is a wrapper around string objects for easier string subclassing.
Example of UserDict in Python
from collections import UserString
# Creating a UserString
user_string = UserString("Welcome to ScholarHat!")
print("UserString:")
print(user_string)
The above program demonstrates the creation of a UserString.
Output
UserString:
Welcome to ScholarHat!
User-Defined Data Structures in Python
1. Linked Lists
A Linked List is a linear data structure consisting of a series of connected nodes randomly stored in the memory. Here, each node consists of two parts, the first part is the data and the second part contains the pointer to the address of the next node.
The first node of a linked list is called the Head, and it acts as an access point. The head pointer points to the first element of the linked list. The last node is called the Tail, and it marks the end of a linked list by pointing to a NULL value.
Example of a Linked List in Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
# Example usage
llist = LinkedList()
llist.head = Node(10)
second = Node(20)
third = Node(30)
llist.head.next = second
second.next = third
llist.printList()
The above program demonstrates the creation of a Linked List and its associated operations.
Output
10
20
30
Read More: Linked List in Data Structures |
2. Stacks
A stack is an ordered list or a container where insertion and deletion can be done from one end known as the top of the stack. The last inserted element is available first and is the first one to be deleted. Hence, it is known as Last In, First Out LIFO, or First In, Last Out FILO.
Stacks are dynamic; this means that they do not have a fixed size and their size can be increased or decreased depending on the number of elements.
Example of a Stack in Python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_empty(self):
return self.items == []
# Example usage
stack = Stack()
stack.push('ScholarHat')
stack.push('DotNetTricks')
print(stack.pop())
The above program demonstrates the creation of a Stack and its associated operations.
Output
DotNetTricks
Read More: Implementing Stack in Data Structures |
3. Queue
A queue is an ordered list in which insertion is done at one end called REAR and deletion at another end called FRONT. The first inserted element is available first for the operations to be performed and is the first one to be deleted. Hence, it is known as First In First Out, FIFO, or Last In Last Out, LILO.
Queues can be implemented in Python using several methods:
1. Using a list
In this implementation method, the append() method is used for enqueue operations, while the pop(0) method is employed for dequeue operations.
Example of a Queue in Python
# Initialize a queue
queue = []
# Enqueue operations
queue.append('Sakshi')
queue.append('Sourav')
queue.append('Pragati')
print("Initial queue:")
print(queue)
# Dequeue operations
print("\nItems removed from the queue:")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after dequeue operations:")
print(queue)
Using collections.deque
Using queue.Queue
The above program demonstrates the creation of a queue using a list and its associated operations.
Output
Initial queue:
['Sakshi', 'Sourav', 'Pragati']
Items removed from the queue:
Sakshi
Sourav
Pragati
Queue after dequeue operations:
[]
2. Using collections.deque
The collections.deque implementation has O(1) time complexity for append and pop operations from both ends, compared to the list's O(n) for certain operations.
Example of a Queue in Python
from collections import deque
# Initialize a queue
queue = deque()
# Enqueue operations
queue.append('Sakshi')
queue.append('Sourav')
queue.append('Pragati')
print("Initial queue:")
print(queue)
# Dequeue operations
print("\nItems removed from the queue:")
print(queue.popleft())
print(queue.popleft())
print(queue.popleft())
print("\nQueue after dequeue operations:")
print(queue)
The above program demonstrates the creation of a queue using collections.deque and its associated operations.
Output
Initial queue:
deque(['Sakshi', 'Sourav', 'Pragati'])
Items removed from the queue:
Sakshi
Sourav
Pragati
Queue after dequeue operations:
deque([])
3. Using queue.Queue
The queue.Queue class provides a FIFO queue implementation suitable for multi-threading environments, with methods to check if the queue is full or empty.
Example of a Queue in Python
from queue import Queue
# Initialize a queue with a specific max size
queue = Queue(maxsize=3)
# Check queue size
print(queue.qsize())
# Enqueue operations
queue.put('Sakshi')
queue.put('Sourav')
queue.put('Pragati')
# Check if the queue is full
print("\nIs the queue full?:", queue.full())
# Dequeue operations
print("\nItems removed from the queue:")
print(queue.get())
print(queue.get())
print(queue.get())
# Check if the queue is empty
print("\nIs the queue empty?:", queue.empty())
The above program demonstrates the creation of a queue using queue.Queue and its associated operations.
Output
0
Is the queue full?: True
Items removed from the queue:
Sakshi
Sourav
Pragati
Is the queue empty?: True
Read More: Queue in Data Structures |
Priority Queue
It is a special type of queue in which each element has a priority assigned to it. The element with the highest priority is removed first.
Example of a Queue in Python
class SimplePriorityQueue:
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue])
# check if the queue is empty
def isEmpty(self):
return len(self.queue) == 0 # Corrected condition
# add an element to the queue
def insert(self, item):
self.queue.append(item)
# Method to remove an element based on priority
def delete(self):
try:
if not self.isEmpty(): # Check if queue is empty
highest_priority = 0
for i in range(1, len(self.queue)): # Start from index 1
if self.queue[i] > self.queue[highest_priority]:
highest_priority = i
item = self.queue[highest_priority]
del self.queue[highest_priority]
return item
else:
raise IndexError("The queue is empty.") # Raise IndexError if queue is empty
except IndexError as e:
print(e)
return None
# Example usage
if __name__ == '__main__':
priorityQueue = SimplePriorityQueue()
priorityQueue.insert(40)
priorityQueue.insert(20)
priorityQueue.insert(50)
priorityQueue.insert(10)
print(priorityQueue) # Displays the queue
while not priorityQueue.isEmpty():
print(priorityQueue.delete()) # Removes elements based on priority
The above program demonstrates the creation of a priority queue and its associated operations.
Output
40 20 50 10
50
40
20
10
Read More: Priority Queue in Data Structures |
4. Tree
A tree is a collection of objects or entities known as nodes connected by edges and has a hierarchical relationship between the nodes.
The topmost node of the tree is called the root node from which the tree originates, and the nodes below it are called the child nodes. Each node can have multiple child nodes, and these child nodes can also have their child nodes, forming a recursive structure.
Example of a Tree in Python
class Tree:
def __init__(self, info, left=None, right=None):
self.info = info
self.left = left
self.right = right
def __str__(self):
return (str(self.info) + ', Left child: ' + str(self.left) + ', Right child: ' + str(self.right))
tree = Tree(1, Tree(2, 2.1, 2.2), Tree(3, 3.1))
print(tree)
The above program demonstrates the creation of a tree in python.
Output
1, Left child: 2, Left child: 2.1, Right child: 2.2, Right child: 3, Left child: 3.1, Right child: None
Read More: Trees in Data Structures - Its Structure, Operations & Applications |
Heap
heapq module in Python provides the heap data structure which is a specialized data structure using Python that follows the heap queue or priority queue algorithm.
A heap is a tree-like data structure in which the tree is a complete binary tree that satisfies the heap property. According to the heap property, all the children of a given node must be greater than the parent node, or all the children must be smaller than the parent node. This type of data structure is also called a binary heap.
Example of a Heap in Python
# Importing the heapq module for heap operations
import heapq
# Initializing a list
my_heap = [50, 20, 3, 70, 6, 8]
# Transforming the list into a heap
heapq.heapify(my_heap)
# Displaying the heap
print("Initial heap:", my_heap)
# Adding an element to the heap
heapq.heappush(my_heap, 4)
# Displaying the modified heap
print("Heap after adding an element:", my_heap)
# Removing and returning the smallest element from the heap
smallest_element = heapq.heappop(my_heap)
# Displaying the removed element
print("Smallest element removed from the heap:", smallest_element)
The above program demonstrates the creation of a heap in python.
Output
Initial heap: [3, 6, 8, 70, 20, 50]
Heap after adding an element: [3, 6, 4, 70, 20, 50, 8]
Smallest element removed from the heap: 3
Read More: Heap in Data Structures |
5. Graph
A graph is a collection of nodes that consist of data and are connected to other nodes of the graph. formally a Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is denoted by G(V, E).
Graphs can be represented in Python using two primary methods:
1. Adjacency Matrix
An Adjacency Matrix is a 2D array of size V x V where V is the number of nodes in a graph. It is used to represent a finite graph, with 0's and 1's. Since it's a V x V matrix, it is known as a square matrix. The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph i.e. if there is any edge connecting a pair of nodes in the graph.
Example of a Graph in Python
class GraphMatrix:
def __init__(self, numVertices):
self.adjMatrix = [[0] * numVertices for _ in range(numVertices)]
self.numVertices = numVertices
def add_edge(self, start, end, weight=1):
self.adjMatrix[start][end] = weight
# For undirected graph, add an edge back
self.adjMatrix[end][start] = weight
def display(self):
print("Adjacency Matrix:")
for row in self.adjMatrix:
print(row)
# Initialize the graph with 5 vertices
graphMatrix = GraphMatrix(5)
# Add edges
edges = [(0, 1), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (3, 4)]
for start, end in edges:
graphMatrix.add_edge(start, end)
# Display the adjacency matrix
graphMatrix.display()
The above program demonstrates the creation of a graph in python.
Output
Adjacency Matrix:
[0, 1, 0, 0, 1]
[1, 0, 1, 1, 1]
[0, 1, 0, 1, 0]
[0, 1, 1, 0, 1]
[1, 1, 0, 1, 0]
2. Adjacency List
An adjacency list represents a graph as an array of linked lists. The index of the array represents a vertex and each element in its linked list represents the other vertices that form an edge with the vertex.
Example of a Graph in Python
class AdjNode:
def __init__(self, value):
self.vertex = value
self.next = None
class GraphList:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
def add_edge(self, src, dest):
# Add an edge from src to dest
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
# Since the graph is undirected, add an edge from dest to src
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def print_graph(self):
for i in range(self.V):
print(f"Adjacency list of vertex {i}", end="")
temp = self.graph[i]
while temp:
print(f" -> {temp.vertex}", end="")
temp = temp.next
print(" \n")
# Initialize the graph with 5 vertices
graphList = GraphList(5)
# Add edges
edges = [(0, 1), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (3, 4)]
for start, end in edges:
graphList.add_edge(start, end)
# Print the adjacency list
graphList.print_graph()
The above program demonstrates the creation of a graph in python.
Output
Adjacency list of vertex 0 -> 4 -> 1
Adjacency list of vertex 1 -> 4 -> 3 -> 2 -> 0
Adjacency list of vertex 2 -> 3 -> 1
Adjacency list of vertex 3 -> 4 -> 2 -> 1
Adjacency list of vertex 4 -> 3 -> 1 -> 0
Read More: Graphs in Data Structures - Types of Graphs, Representation & Operations |
6. HashMaps
HashMaps are like dictionaries in Python. They store key-value pairs. HashMaps uses a hash function to compute an index for each key, which leads to efficient retrieval and insertion.
Example of a HashMap in Python
class HashMap:
def __init__(self, size):
self.size = size
self.map = [None] * size
def _hash(self, key):
return hash(key) % self.size
def add(self, key, value):
index = self._hash(key)
if self.map[index] is None:
self.map[index] = []
self.map[index].append((key, value))
def get(self, key):
index = self._hash(key)
if self.map[index] is not None:
for pair in self.map[index]:
if pair[0] == key:
return pair[1]
return None
def remove(self, key):
index = self._hash(key)
if self.map[index] is not None:
for i, pair in enumerate(self.map[index]):
if pair[0] == key:
del self.map[index][i]
return
# Example usage:
if __name__ == "__main__":
my_map = HashMap(10)
my_map.add("apple", 10)
my_map.add("banana", 20)
my_map.add("orange", 30)
print(my_map.get("apple"))
print(my_map.get("banana"))
print(my_map.get("orange"))
my_map.remove("banana")
print(my_map.get("banana"))
The above program demonstrates the creation of a HashMap in python.
Output
10
20
30
None
Read More: Hashing in Data Structures |
Summary
Hence, in the above article, we saw all the prominent data structures in Python. Python's native data structures, including lists, dictionaries, tuples, and sets, offer a robust basis for storing and managing data in various ways. The user-defined data structures, such as stacks, arrays, queues, etc., reveal numerous avenues for creative problem-solving endeavors.