Working with Lists, Tuples, and Dictionaries

Introduction to Python for GIS

Video Locked

Please log in to watch this video

Log In
Chapter Info
Course The Ultimate GeoPython course
Module Introduction to Python for GIS
Chapter Working with Lists, Tuples, and Dictionaries
Navigation

Chapter Content

Python provides powerful collection types to store and manage groups of related data. In this post, we’ll focus on three core collections—lists, tuples, and dictionaries—exploring their characteristics, common operations, and best practices. Let’s get started!

1. Lists: Ordered, Mutable Sequences

A list is an ordered collection that can hold elements of any type. You can add, remove, or modify items.

# Creating a list
fruits = ["apple", "banana", "cherry"]
print(fruits)           # ['apple', 'banana', 'cherry']

# Adding items
fruits.append("date")
fruits.insert(1, "blueberry")
print(fruits)           # ['apple', 'blueberry', 'banana', 'cherry', 'date']

# Removing items
fruits.remove("banana")
popped = fruits.pop()   # removes and returns last item
print(popped)           # 'date'
print(fruits)           # ['apple', 'blueberry', 'cherry']

# Accessing & slicing
print(fruits[0])        # 'apple'
print(fruits[1:3])      # ['blueberry', 'cherry']

# Iterating
for fruit in fruits:
    print(fruit)

Do’s:

  • Use lists when you need to maintain order and modify elements.

  • Use list comprehensions for concise transformations:

    lengths = [len(f) for f in fruits]

Don’ts:

  • Avoid modifying a list while iterating—this can lead to skipped elements or unexpected behavior.

    # ❌ Risky:
    for f in fruits:
        if f.startswith('b'):
            fruits.remove(f)

2. Tuples: Ordered, Immutable Sequences

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

# Creating tuples
dimensions = (1920, 1080)
colors = 'red', 'green', 'blue'  # parentheses optional

# Accessing & unpacking
width, height = dimensions
print(width, height)   # 1920 1080

# Single-element tuple (note trailing comma)
single = (42,)
print(type(single))    # <class 'tuple'>

Do’s:

  • Use tuples for fixed collections or heterogenous records (e.g., coordinates).

  • Leverage tuple unpacking for clear assignment.

Don’ts:

  • Don’t try to assign to tuple elements: they’re read-only.

  • Avoid using tuples for collections you intend to modify.

3. Dictionaries: Key–Value Mappings

A dictionary stores data in key–value pairs for fast lookups.

# Creating a dict
student = {
    "name": "Alice",
    "age": 24,
    "courses": ["Math", "Science"]
}

# Access & update
print(student['name'])   # 'Alice'
student['age'] = 25

# Adding & removing
student['grade'] = 'A'
popped = student.pop('courses')
print(popped)            # ['Math', 'Science']

# Iterating
elements = list(student.items())  # [('name','Alice'),('age',25),('grade','A')]
for key, value in student.items():
    print(f"{key}: {value}")

Do’s:

  • Use dictionaries when you need named fields or fast lookups.

  • Use .get() with a default to avoid KeyErrors:

    value = student.get('email', 'Not provided')

Don’ts:

  • Don’t use mutable types (like lists) as keys—they must be hashable.

  • Avoid accessing keys directly if you’re unsure they exist; prefer .get().

4. When to Use Which Collection

Scenario Use
Ordered, changeable sequence List
Fixed set of values Tuple
Unique, unordered items Set
Key-based lookup or named fields Dict

5. Common Pitfalls & Tips

  • List vs. Tuple confusion: Remember tuples are immutable.

  • Mutable default argument: Don’t use def f(x=[]):—use None instead and initialize inside.

  • Dictionary key errors: Use .get() or in to check for key existence.

# Safe dict access:
if 'age' in student:
    print(student['age'])