Lists & Tuples

Lists and Tuples are used to store multiple items in a single variable. The main difference is that Lists are mutable (changeable) and Tuples are immutable.

1. Python Lists

fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add
fruits[1] = "blueberry" # Change
print(fruits) # ["apple", "blueberry", "cherry", "orange"]

2. Tuples (The Constant List)

Tuples are defined with parentheses and cannot be changed after creation.

point = (10, 20)
# point[0] = 5 # ERROR: Cannot change a tuple

3. Slicing Sequences

Python has a powerful slicing syntax: [start:stop:step].

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:5])   # [2, 3, 4]
print(nums[::2])    # [0, 2, 4, 6, 8] (Step of 2)
print(nums[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (Reverse)

4. List Methods

  • .pop(): Removes the last item.
  • .sort(): Sorts in place.
  • .clear(): Empties the list.
  • .extend(): Adds another list to the end.
When to use which? Use a List when you need to change elements frequently. Use a Tuple when you want to protect your data from accidental modification.