Core Structure

Lists, Tuples, and Dictionaries: Python’s Core Structures

Introduction

Data structures are fundamental to any programming language, and Python provides several built-in options for managing collections of data. In this post, we’ll explore lists, tuples, and dictionaries—their characteristics, use cases, and common operations.


1. Lists: Mutable and Ordered

A list is a mutable, ordered collection of items. You can store any type of data in a list, and it can even mix types.

Creating Lists

python
Copy code
# Empty list
my_list = []

# List with values
fruits = ["apple", "banana", "cherry"]

Accessing Elements

python
Copy code
print(fruits[0])  # First element: "apple"
print(fruits[-1])  # Last element: "cherry"

Common List Operations

python
Copy code
fruits.append("orange")  # Add an element
fruits.remove("banana")  # Remove an element
fruits[1] = "grape"  # Modify an element
print(len(fruits))  # Get the length

Iterating Over a List

python
Copy code
for fruit in fruits:
    print(fruit)

When to Use Lists

  • Storing a collection of items where order matters.
  • When you need to frequently modify the collection.

2. Tuples: Immutable and Ordered

A tuple is similar to a list but immutable, meaning you cannot change its contents once created.

Creating Tuples

python
Copy code
# Empty tuple
my_tuple = ()

# Tuple with values
coordinates = (10, 20)

# Single-element tuple (note the comma)
single = (5,)

Accessing Elements

python
Copy code
print(coordinates[0])  # First element: 10

Key Features

  • Tuples are faster than lists.
  • Commonly used for fixed collections of items (e.g., coordinates, settings).

When to Use Tuples

  • Data integrity: Use tuples to ensure data cannot be modified.

  • Returning multiple values from a function:

    python
    Copy code
    def get_point():
        return (10, 20)
    
    x, y = get_point()

3. Dictionaries: Key-Value Pairs

A dictionary is an unordered collection of key-value pairs, where each key maps to a value.

Creating Dictionaries

python
Copy code
# Empty dictionary
my_dict = {}

# Dictionary with values
person = {"name": "Alice", "age": 30, "city": "New York"}

Accessing and Modifying Data

python
Copy code
# Access value by key
print(person["name"])  # Output: "Alice"

# Add or modify key-value pairs
person["job"] = "Engineer"
person["age"] = 31

# Remove a key-value pair
del person["city"]

Common Dictionary Operations

python
Copy code
# Check if a key exists
print("name" in person)  # Output: True

# Iterate through keys
for key in person:
    print(key)

# Iterate through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

When to Use Dictionaries

  • Representing data with named attributes.
  • Fast lookups by key (e.g., a phone book or settings).

4. Comparison: Lists vs. Tuples vs. Dictionaries

Feature List Tuple Dictionary
Mutable Yes No Yes
Ordered Yes Yes No (insertion order since Python 3.7)
Use Case General-purpose Fixed collections Key-value mappings

5. Practical Example

Problem: Managing a Shopping List

Let’s combine lists and dictionaries to solve a real-world problem.

Code Example:

python
Copy code
# Shopping list with item names and quantities
shopping_list = [
    {"item": "apple", "quantity": 5},
    {"item": "banana", "quantity": 3},
    {"item": "milk", "quantity": 1}
]

# Add a new item
shopping_list.append({"item": "bread", "quantity": 2})

# Update quantity
for item in shopping_list:
    if item["item"] == "milk":
        item["quantity"] += 1

# Print the shopping list
for item in shopping_list:
    print(f"{item['item']}: {item['quantity']}")

Conclusion

Lists, tuples, and dictionaries are versatile tools in Python for organizing and working with data. By mastering these core data structures, you’ll be prepared to tackle more complex tasks and advanced structures.