Python Data Structures
Python is a versatile language, largely because of its powerful and flexible data structures. Understanding these structures is crucial for writing efficient and clean code. In this guide, we’ll explore the four core Python data structures: lists, tuples, sets, and dictionaries. Each comes with its own strengths, use cases, and unique behaviors.
1. Lists
Lists are one of the most commonly used data structures in Python. They are ordered, mutable, and allow duplicate elements.
Creating and Accessing Lists
# Creating a list
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
# Accessing elements
print(fruits[0])   # Output: apple
print(numbers[-1]) # Output: 5
Indexing and Slicing
Python lists support indexing and slicing:
print(fruits[1:])   # ['banana', 'cherry']
print(numbers[:3])  # [1, 2, 3]
Common List Methods
Lists come with many built-in methods:
fruits.append("orange")       # Add element
fruits.extend(["kiwi","melon"]) # Add multiple elements
fruits.insert(1, "mango")    # Insert at specific index
fruits.remove("banana")       # Remove element
fruits.pop()                  # Remove last element
fruits.sort()                 # Sort the list
fruits.reverse()              # Reverse the list
List Comprehensions
Python supports concise list creation using list comprehensions:
squares = [x**2 for x in range(1, 6)]
even_numbers = [x for x in range(10) if x % 2 == 0]
Nested Lists
Lists can contain other lists, forming nested lists:
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[1][2])  # Output: 6
Shallow vs Deep Copy
- Shallow copy copies references; modifying nested elements affects both lists.
 - Deep copy duplicates nested elements completely.
 
import copy
original = [[1,2], [3,4]]
shallow = original.copy()
deep = copy.deepcopy(original)
Practical Use Cases
- Storing sequences of elements
 - Iterating over items
 - Implementing stacks and queues
 
2. Tuples
Tuples are immutable sequences in Python. They are similar to lists but cannot be modified after creation.
Tuple Creation and Immutability
t = (1, 2, 3)
single_element = (5,)  # Note the comma
Tuple Packing and Unpacking
# Packing
person = ("Alice", 25, "Engineer")
# Unpacking
name, age, profession = person
Accessing Elements
Tuples support indexing and slicing like lists:
print(person[0])   # Alice
print(person[1:])  # (25, 'Engineer')
Tuple Methods
Tuples have very few methods due to immutability:
t = (1, 2, 3, 2)
print(t.count(2))  # 2
print(t.index(3))  # 2
Comparison with Lists
- Tuples are faster due to immutability.
 - Tuples are safe for fixed collections.
 - Lists are better when you need to modify data frequently.
 
3. Sets
Sets are unordered collections of unique elements. They are mutable, while frozensets are immutable.
Creating Sets and Frozensets
s = {1, 2, 3, 3}  # Duplicate automatically removed
fs = frozenset([4,5,6])
Mathematical Operations
a = {1,2,3}
b = {3,4,5}
print(a.union(b))            # {1,2,3,4,5}
print(a.intersection(b))     # {3}
print(a.difference(b))       # {1,2}
print(a.symmetric_difference(b))  # {1,2,4,5}
Set Methods and Use Cases
s.add(4)
s.remove(2)
s.pop()  # Removes arbitrary element
s.clear() # Empties the set
Use Cases:
- Removing duplicates from lists
 - Membership testing
 - Set algebra operations in algorithms
 
4. Dictionaries
Dictionaries are unordered, mutable collections of key-value pairs. They are extremely versatile and widely used.
Creating and Accessing Dictionaries
person = {"name":"Alice", "age":25, "profession":"Engineer"}
# Access
print(person["name"])
print(person.get("age"))
Adding, Updating, and Deleting Elements
person["location"] = "Delhi"   # Add
person["age"] = 26             # Update
del person["profession"]       # Delete
person.pop("location")         # Remove and return value
Dictionary Methods
print(person.keys())    # dict_keys(['name', 'age'])
print(person.values())  # dict_values([Alice, 26])
print(person.items())   # dict_items([('name','Alice'),('age',26)])
Nested Dictionaries
students = {
    "Alice": {"age": 25, "grade": "A"},
    "Bob": {"age": 22, "grade": "B"}
}
print(students["Alice"]["grade"])  # A
Iterating Over Dictionaries
for key, value in person.items():
    print(key, "->", value)
Practical Dictionary-Based Problems
- Counting frequency of elements
 - Mapping unique IDs to data
 - Storing JSON-like hierarchical data
 
Conclusion
Python’s core data structures — lists, tuples, sets, and dictionaries — form the foundation of programming in Python. Each has its strengths and ideal use cases:
- Use lists for ordered, mutable collections.
 - Use tuples for fixed, immutable sequences.
 - Use sets for unique elements and mathematical operations.
 - Use dictionaries for key-value mappings and fast lookups.
 
Mastering these structures not only improves your coding efficiency but also opens doors to advanced topics like algorithm optimization, data analysis, and software design.
                                                
                                                                
                                                                
                                                                
                                                                
                                                                
                                                                
                                                                
                                                                
                                                                