Exploring Python Data Structures

Introduction

Data structures are essential building blocks of computer programs that allow for efficient storage, organization, and manipulation of data. They enable programmers to structure and manage data in a way that optimizes various operations such as searching, inserting, deleting, and accessing elements. Python, being a versatile programming language, provides a rich set of data structures in its standard library. These built-in data structures are readily available for use, making it easier for developers to handle and process data effectively. In this article, we will explore some of the frequently used data structures in Python.

Table of Contents

  • Linear Data Structures 
  • Non-Linear Data Structures
  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • Conclusion
  • FAQ's

Liner Data Structures

Linear data structures are collections of data elements arranged in a sequential manner, where each element is connected to its previous and next element. They allow access to their elements in a linear order, sequential manner like an array, array lists, stacks, etc. Below are some of the commonly used linear data structures in Python.

Array in Python

The arrays can hold a fixed number of items, and these items should be of the same type. In Python, arrays are created using the 'array' module. Arrays are faster than lists as they use contiguous memory allocations. However, arrays have a fixed size, so they cannot be dynamically resized. The basic operations supported by an array are as stated below.

  • Traverse: print all the array elements one by one.
  • Insertion: Adds an element at the given index.
  • Deletion: Deletes an element at the given index.
  • Search: Searches an element using the given index or by the value.
  • Update: Updates an element at the given index.

Syntax

import array 
arrayName = array(typecode, [Initializers])

Example 

import array as arr

numbers = arr.array('i', [2, 4, 5, 6])

def traverse(array):
    print("Array elements:")
    for element in array:
        print(element, end=" ")
    print()

def insertion(array, index, value):
    array.insert(index, value)

def deletion(array, index):
    if index < len(array):
        del array[index]
    else:
        print("Invalid index. Cannot delete element.")

def search_by_index(array, index):
    if index < len(array):
        print(f"Element at index {index}: {array[index]}")
    else:
        print("Invalid index. Element not found.")

def search_by_value(array, value):
    try:
        index = array.index(value)
        print(f"Element {value} found at index {index}.")
    except ValueError:
        print(f"Element {value} not found in the array.")

def update(array, index, new_value):
    if index < len(array):
        array[index] = new_value
    else:
        print("Invalid index. Cannot update element.")


# Example usage of the array operations
traverse(numbers)   # Array elements: 2 4 5 6

insertion(numbers, 0, 1)
traverse(numbers)   # Array elements: 1 2 4 5 6

deletion(numbers, 2)
traverse(numbers)   # Array elements: 1 2 5 6

search_by_index(numbers, 1)   # Element at index 1: 2
search_by_value(numbers, 5)   # Element 5 found at index 2

update(numbers, 3, 7)
traverse(numbers)   # Array elements: 1 2 5 7

Output

Output

Stacks in Python

A stack is a collection of elements that supports two main operations push and pop. Push adds an element to the top of the stack, while pop delete adds an element inserted in the last sequence. Such features are known as Last in-First Out. We can perform different actions on a stack.

  • empty(): It returns true if the stack is empty.
  • size(): It returns the length of the stack.
  • top(): This method returns an address of the last element of the stack.
  • push(g): This method adds the element 'g' at the end of the stack.
  • pop(): This method removes the topmost element of the stack.

Syntax

#stack creation
stack_example = []
#stack method
stack.method('element')

Example

# Initialize an empty stack
stack = []
max_size = 5

def empty():
    return len(stack) == 0

def size():
    return len(stack)

def top():
    if not empty():
        return stack[-1]
    else:
        return None

def push(element):
    if len(stack) >= max_size:
        print("Stack is full. Cannot push element.")
    else:
        stack.append(element)
        print(f"Pushed {element} to the stack.")

def pop():
    if not stack:
        print("Stack is empty. Cannot pop element.")
    else:
        element = stack.pop()
        print(f"Popped {element} from the stack.")
        return element

# Example usage of the stack operations
print("Is the stack empty?", empty())  # Output: Is the stack empty? True

push(10)
push(20)
push(30)

print("Stack size:", size())      # Output: Stack size: 3
print("Top element:", top())      # Output: Top element: 30

popped_element = pop()
print("Popped element:", popped_element)  # Output: Popped element: 30
print("Stack size after pop:", size())    # Output: Stack size after pop: 2
print("Top element after pop:", top())    # Output: Top element after pop: 20

Output

Output

Queue in Python

The queue is a linear data structure with a rear and a front end, similar to a stack. It stores items sequentially in a FIFO (First In First Out) manner. A queue is a collection of elements that supports two main operations enqueue and dequeue. Enqueue adds an element to the end of the queue, while dequeue removes the front element from the queue. In Python, you can use a list or the 'queue' module to implement a queue. Some common queue methods

  • put(item): Inserts an element to the queue
  • get(): Gets an element from the queue
  • empty(): Checks and returns true if the queue is size
  • size(): Returns queue's length
  • full(): Checks and returns true if the queue is full.

Syntax

# Initialize a queue
queue_exm = []
#Queue method
queue_exm.method('element')

Example

queue = []
max_size = 5

def put(item):
    if len(queue) >= max_size:
        print("Queue is full. Cannot insert element.")
    else:
        queue.append(item)
        print(f"Inserted {item} to the queue.")

def get():
    if not queue:
        print("Queue is empty. Cannot get element.")
        return None
    else:
        item = queue.pop(0)
        print(f"Got {item} from the queue.")
        return item

def empty():
    return len(queue) == 0

def size():
    return len(queue)

def full():
    return len(queue) == max_size


# Example usage of the queue operations
print("Is the queue empty?", empty())  # True

put(1)
put(2)
put(3)
put(4)
put(5)

print("Is the queue full?", full())  # True

put(6)  # Queue is full. Cannot insert element.

print("Queue size:", size())  # Queue size: 5

get()  # Got 1 from the queue.
get()  # Got 2 from the queue.

print("Is the queue empty?", empty())  # False

Output

Output

 

Non-Liner Data Structures

These are the data structures in which there is no sequential linking of data elements. Any pair or group of data elements can be linked to each other and can be accessed without a strict sequence.

  • Binary Tree: Where each data element can be connected to a maximum of two other data elements, and it starts with a root node.
  • Heap: Where the data in the parent node is either strictly greater than/equal to the child nodes or strictly, it's than its child nodes.
  • Hash Table: Data structure which is made of arrays associated with each other using a hash function. It retrieves values using keys ratan than index from a data element.

Python supports a few more data structures that are mentioned below.

Lists in Python

A list is a collection of elements of different data types. Lists are very flexible and can be resized dynamically as it is the most versatile datatype available in Python. It can be written as a list of comma-separated values (items) between square brackets.

Syntax

List_A = [item 1, item 2, item 3….., item n]

Example

lst = [1, 2, 'a', 'b']
print(lst)

Output

Output

Tuples in Python

A tuple is an immutable collection of elements of different data types i.e. once a tuple is created, its elements cannot be modified. They are normally written inside parentheses to distinguish them from lists using square brackets and are also faster than lists as they are stored in contiguous memory locations.

Syntax

tup = (element1, element2,...,elementn)

Example

tup = (1, 2, 'a', 'b')
print(tup)

Output

Output

Dictionaries in Python

A dictionary is a collection of key-value pairs. Pair are separated by a colon, and different pairs are separated by commas. Keys are unique within a dictionary, while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type, such as strings, numbers, or tuples.

Syntax

dict = {'Key': 'Value', 'Key': 'Value', 'Key': 'Value'}

Example

dict = {'name': 'John', 'age': 25, 'gender': 'male'}
print(dict)

Output

Output

Sets in Python

A set is an unordered collection of unique elements which means that even if the data is repeated more than one time, it would be entered into the set only once. Sets are useful for removing duplicates from a list and performing set operations like union, intersection, and difference. The elements in the set are immutable, but the set as a whole is mutable, and there is no index attached to any element in a Python set. So they do not support any indexing or slicing operation.

Syntax

s = set([elements])

Example

s = set([1, 2, 3, 3, 4, 5])
print(s)

Output

Output

Conclusion

Data structures are fundamental concepts of computer science that help us for writing efficient programs in any language. Python is a high-level, interpreted, interactive, and object-oriented scripting language which supports a variety of data structures. The data structures are all used for storing data for different purposes, like arrays when we need to store similar data together; lists are useful to hold a heterogeneous collection of related objects. We need dictionaries whenever we need to link a key to a value and to quickly access some data by a key, like in a real-world dictionary, sets allow us to perform operations, such as intersection or difference, on them; thus, they are useful for comparing two sets of data, tuples are similar to lists but are immutable; they can be used as data containers that we do not want to modify by mistake, etc.

FAQ's

Question. What is the difference between an array and a list in Python?

Answer. In Python, an array is a fixed-size collection of elements of the same type, while a list is a dynamic collection that can hold elements of different types. Arrays are generally faster for certain operations, as they use contiguous memory allocations, whereas lists are more flexible and can be resized easily.

Question. What is the purpose of a stack data structure?

Answer. A stack is a data structure that follows the Last In, First Out (LIFO) principle. It is mainly used to store and retrieve data in a specific order. Elements are added or removed from the top of the stack using push and pop operations, respectively.

Question. How can I implement a queue in Python?

Answer. You can implement a queue in Python using a list or the 'queue' module. The 'queue' module provides the Queue class, which supports operations like enqueue (put), dequeue (get), checking if the queue is empty, getting the queue's length, etc.

Question. What are some examples of non-linear data structures in Python?

Answer. Some examples of non-linear data structures in Python include binary trees, heaps, hash tables, and graphs. These data structures allow for more complex relationships between data elements than linear ones.

Question. What is the difference between a list and a tuple in Python?

Answer. The main difference between a list and a tuple in Python is mutability. Lists are mutable, meaning their elements can be modified, added, or removed. On the other hand, tuples are immutable, and once created, their elements cannot be modified. Tuples are typically used to store a collection of related values that should not be changed.

Question. When should I use a dictionary in Python?

Answer. Dictionaries are used when you need to associate a key with a value and quickly access the data using the key. They are useful for tasks like indexing, mapping, and storing related information. Dictionaries are efficient for looking up values based on their associated keys.

Question. How are sets different from lists and tuples?

Answer. Sets are unordered collections of unique elements, meaning they do not allow duplicate values. Unlike lists and tuples, sets do not support indexing or slicing operations. Sets are often used for removing duplicates from a list or performing set operations like union, intersection, and difference.

Question. Are there any built-in data structures in Python?

Answer. Yes, Python provides several built-in data structures in its standard library, such as lists, tuples, dictionaries, sets, arrays (from the 'array' module), queues (from the 'queue' module), etc. These data structures offer different functionalities and can be used based on specific requirements.


Recommended Free Ebook
Similar Articles