Chapter 9: Tuples, Lists, and Dictionaries

This chapter introduces tuples, lists, and dictionaries.

9.1 Tuples, Lists, and Dictionaries

Lists are ordered collections of items that can be of different types and are mutable (changeable). Lists are one of the four built-in data structures in Python.

9.2 Lists

Creating Lists

You can create lists using square brackets or the list() constructor:

# Empty list
empty_list = []

# List with items
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]

List Indexing and Slicing

Access list elements using index starting from 0:

fruits = ["apple", "banana", "orange"]
print(fruits[0])  # "apple"
print(fruits[-1]) # "orange" (last element)

# Slicing
print(fruits[1:3]) # ["banana", "orange"]

Modifying Lists

  • Change an item: fruits[1] = "grape"
  • Add an item: fruits.append("kiwi")
  • Insert at position: fruits.insert(1, "pear")
  • Remove an item: fruits.remove("banana")
  • Remove by index: del fruits[2]
  • Pop last item: last_fruit = fruits.pop()

List Methods

Common list methods include:

  • len(list): Get the length
  • list.sort(): Sort the list in place
  • list.reverse(): Reverse the list in place
  • list.index(item): Find index of item
  • list.count(item): Count occurrences of item

9.4 Sorting Lists

The sorted() Function

The sorted() function returns a new sorted list:

numbers = [3, 1, 4, 1, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 1, 3, 4, 5]

9.6 Dictionaries

Dictionaries are unordered collections of key-value pairs. They allow you to store and retrieve data using descriptive keys instead of numerical indexes like lists.

9.3 Tuples

What Are Tuples?

Tuples are immutable ordered sequences, similar to lists but cannot be modified after creation. They are defined using parentheses:

# Creating tuples
empty_tuple = ()
single_item = ("hello",)
coordinates = (3.14, 2.71, 1.41)
person = ("Alice", 30, "Engineer")

Tuple Immutability

Once created, tuple elements cannot be changed:

coordinates = (3.14, 2.71, 1.41)
# coordinates[0] = 3.0  # TypeError!

# But you can create new tuples
coordinates = (3.0,) + coordinates[1:]  # Creates new tuple

Tuple Unpacking

Multiple assignment works well with tuples:

name, age, profession = ("Alice", 30, "Engineer")
print(name, age, profession)  # Alice 30 Engineer

# Swapping values
a = 5
b = 10
a, b = b, a  # a=10, b=5

When to Use Tuples vs Lists

  • Tuples: For data that should not change (immutable)
  • Lists: For collections that need modification
  • Lists: When you need features like append(), insert(), remove()
  • Tuples: Can be used as dictionary keys (lists cannot)

9.5 More List Operations

List Comprehensions

Compact way to create new lists from existing ones:

# Create squares of numbers 1-5
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# With condition
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)  # [4, 16, 36, 64, 100]

Copying Lists

Shallow vs Deep Copy:

original = [1, 2, [3, 4]]

# Shallow copy - nested lists share references
shallow = original[:]
shallow[2][0] = 99
print(original)  # [1, 2, [99, 4]]

import copy
deep = copy.deepcopy(original)
deep[2][0] = 88
print(original)  # Still [1, 2, [99, 4]]

9.7 Dictionaries

Creating Dictionaries

# Empty dictionary
empty_dict = {}

# Dictionary with items
person = {
    "name": "Alice",
    "age": 30,
    "profession": "Engineer"
}

# Using dict() constructor
coordinates = dict(x=10, y=20, z=30)

Accessing Dictionary Values

person = {"name": "Alice", "age": 30}

print(person["name"])  # Alice

# Using get() to avoid KeyError
print(person.get("salary", "Not specified"))  # Not specified

# Check if key exists
if "name" in person:
    print("Name found:", person["name"])

Modifying Dictionaries

person = {"name": "Alice", "age": 30}

# Add new key-value pair
person["profession"] = "Engineer"

# Update existing value
person["age"] = 31

# Remove items
del person["age"]
profession = person.pop("profession", "Not specified")

# Get all keys/values/items
keys = person.keys()
values = person.values()
items = person.items()

9.8 Debugging Collections

Common List Issues

  • IndexError: Trying to access nonexistent index
  • TypeError: Wrong operations on data types
  • Modifying while iterating: Exception or unexpected behavior
  • Shallow copy traps: Nested objects aren't copied deeply

Dictionary Debugging

  • KeyError: Accessing non-existent key
  • KeyError vs None: Different behaviors
  • Mutable keys: Lists can't be dictionary keys
  • Iteration behavior: Order of insertion preserved in Python 3.7+
# Debug dictionary operations
person = {"name": "Alice", "age": 30}

# Check keys before access
key = "salary"
if key in person:
    print(f"{key}: {person[key]}")
else:
    print(f"{key} not found")

# Use get() for safety
salary = person.get("salary", "Not available")
print(f"Salary: {salary}")

# Print dictionary contents for debugging
print("Person dict:", person)
print("Keys:", list(person.keys()))
print("Values:", list(person.values()))

Chapter Summary

This chapter introduces tuples, lists, and dictionaries, three fundamental data structures in Python. Lists are mutable sequences, tuples are immutable sequences, and dictionaries are unordered collections of key-value pairs.

These data structures form the backbone of most Python programs, enabling complex data manipulation and storage.

100%