Python - Lists & Tuples

Overview

Estimated time: 30–40 minutes

Work with lists and tuples: creation, indexing, slicing, methods, and when to choose one over the other.

Learning Objectives

  • Create and manipulate lists and tuples safely.
  • Use slicing effectively to copy or extract subsequences.
  • Decide when immutability (tuples) is beneficial.

Prerequisites

Lists

nums = [10, 20, 30]
nums.append(40)
print(nums[1])
print(nums[:2])

Expected Output: 20\n[10, 20]

Tuples

pt = (3, 4)
print(len(pt))
# pt[0] = 5  # TypeError: immutable

Expected Output: 2

Common Pitfalls

  • Confusing shallow copy via slicing vs deep copy for nested lists.
  • Trying to modify a tuple (immutable); use a list if mutation is needed.

Checks for Understanding

  1. How do you copy a list?
  2. When would you prefer a tuple to a list?
Show answers
  1. new = old[:] or list(old) (shallow copy).
  2. When you want immutability and to signal fixed-size, read-only data.

Exercises

  1. Slice a list to get the last two elements.
  2. Unpack a tuple (x, y) and print a formatted string.