Introduction to Data Structures in Python

Data structures are essential for organizing, managing, and storing data efficiently. Python provides several built-in data structures that are easy to use and highly versatile. This guide will cover:

  1. Lists
  2. Tuples
  3. Sets
  4. Dictionaries
  5. Advanced Data Structures (Optional)

Data Structures in Python - Lists

A list is an ordered, mutable collection of items. It can hold items of different data types.

Creating a List:

fruits = ["apple", "banana", "cherry"]
print(fruits)

Key Operations:

OperationExampleOutput
Access an itemfruits[1]"banana"
Add an itemfruits.append("orange")["apple", "banana", "cherry", "orange"]
Remove an itemfruits.remove("banana")["apple", "cherry"]
Length of listlen(fruits)3
Sort the listfruits.sort()["apple", "banana", "cherry"]

Example:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits)  # Output: ['apple', 'cherry', 'orange']

Data Structures in Python -Tuples

A tuple is an ordered, immutable collection of items.

Creating a Tuple:

coordinates = (10, 20, 30)
print(coordinates)

Key Operations:

OperationExampleOutput
Access an itemcoordinates[1]20
Length of tuplelen(coordinates)3
Tuple unpackingx, y, z = coordinatesx=10, y=20, z=30

Example:

coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z)  # Output: 10 20 30

Data Structures in Python-Sets

A set is an unordered collection of unique items.

Creating a Set:

unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers)  # Output: {1, 2, 3, 4}

Key Operations:

OperationExampleOutput
Add an itemunique_numbers.add(5){1, 2, 3, 4, 5}
Remove an itemunique_numbers.remove(3){1, 2, 4}
Check membership2 in unique_numbersTrue
Unionset1.union(set2)Combined sets
Intersectionset1.intersection(set2)Common items

Example:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2))       # Output: {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # Output: {3}

Data Structures in Python-Dictionaries

A dictionary is an unordered collection of key-value pairs.

Creating a Dictionary:

person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)

Key Operations:

OperationExampleOutput
Access a valueperson["name"]"Alice"
Add a key-value pairperson["job"] = "Developer"Adds job key
Remove a key-valuedel person["age"]Removes age
Get keysperson.keys()["name", "city", "job"]
Get valuesperson.values()["Alice", "New York", "Developer"]

Example:

person = {"name": "Alice", "age": 25}
person["city"] = "New York"
del person["age"]
print(person)  # Output: {'name': 'Alice', 'city': 'New York'}

Advanced Data Structures

Nested Lists and Dictionaries:

  • Nested List Example:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[1][2])  # Output: 6

Nested Dictionary Example:

employees = {
    "emp1": {"name": "Alice", "age": 25},
    "emp2": {"name": "Bob", "age": 30}
}
print(employees["emp1"]["name"])  # Output: Alice

Best Practices for Using Data Structures

  • Choose the Right Data Structure:

    • Use lists for ordered collections.
    • Use tuples for immutable data.
    • Use sets for unique items.
    • Use dictionaries for key-value mappings.
  • Avoid Nested Structures When Possible:

    • Keep data structures simple to enhance readability.
  • Use List Comprehensions:

    • Example:
squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

Handle Missing Keys in Dictionaries:

  • Use .get() to handle missing keys:
print(person.get("job", "Not Found"))  # Output: Not Found

Use Built-in Methods:

  • Take advantage of Python’s powerful built-in methods like sort(), keys(), and intersection().