Python Lists & Tuples · Storing Collections of Data

Mingming Li — Click any blue heading below to expand the content.

Table of Contents

1. What is a list?

A list is a collection that can hold multiple items. Lists are mutable (you can change, add, or remove items). They are created using square brackets [ ].

Think of a list like a shopping list. You can add items, remove items, cross things off, and change your mind.
# List examples
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]   # Lists can mix types!
empty = []

print(fruits)    # ['apple', 'banana', 'cherry']
print(fruits[0]) # 'apple' (first item)
Key property: Lists are ordered, changeable, and allow duplicate values.

2. List operations and methods

# Creating a list
colors = ["red", "green", "blue"]

# Accessing elements (indexing starts at 0!)
print(colors[0])    # "red"
print(colors[-1])   # "blue" (negative counts from end)

# Slicing (getting a portion)
print(colors[0:2])  # ['red', 'green'] (up to but not including index 2)

# Changing elements (mutable!)
colors[1] = "yellow"
print(colors)       # ['red', 'yellow', 'blue']

# Adding elements
colors.append("purple")     # add to end
colors.insert(1, "orange")  # insert at position 1

# Removing elements
colors.remove("yellow")     # remove by value
last = colors.pop()         # remove and return last element
colors.pop(1)               # remove element at index 1

# Other useful methods
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()              # [1, 1, 3, 4, 5, 9]
numbers.reverse()           # reverse order
numbers.count(1)            # 2 (how many times 1 appears)
numbers.index(4)            # 3 (position of first 4)
len(numbers)                # length of list

# Check if element exists
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("Found apple!")

3. What is a tuple?

A tuple is similar to a list, but it is immutable (cannot be changed after creation). Tuples are created using parentheses ( ).

Think of a tuple like a fixed record. Once created, it never changes. Great for things like coordinates, dates, or RGB colors.
# Tuple examples
colors = ("red", "green", "blue")
numbers = (1, 2, 3, 4, 5)
single_item = (42,)   # Note: comma is needed for single-item tuple!
empty = ()

# Accessing elements (same as lists)
print(colors[0])    # "red"
print(colors[-1])   # "blue"

# Slicing works too
print(colors[0:2])  # ('red', 'green')

# Tuples are faster and use less memory than lists
# BUT you CANNOT change them:
# colors[0] = "yellow"  # ERROR! Tuples are immutable
Key property: Tuples are ordered, unchangeable, and allow duplicate values. Once created, you cannot add, remove, or change elements.

4. Tuple operations

# Creating tuples
point = (10, 20)
coordinates = (x, y, z)

# Accessing elements (read-only!)
print(point[0])   # 10

# Concatenation (creates a NEW tuple)
t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = t1 + t2      # (1, 2, 3, 4, 5, 6)

# Repetition
t4 = (1, 2) * 3   # (1, 2, 1, 2, 1, 2)

# Tuple methods (only two!)
t = (1, 2, 3, 2, 4, 2)
t.count(2)        # 3 (how many times 2 appears)
t.index(3)        # 2 (position of first 3)

# Check if element exists
if 10 in point:
    print("Found 10!")

# length
len(t)            # 6

# Converting between list and tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)     # (1, 2, 3)
back_to_list = list(my_tuple) # [1, 2, 3]

# Tuple unpacking (very useful!)
coordinates = (100, 200)
x, y = coordinates   # x=100, y=200

5. List vs Tuple - When to use which?

Feature List Tuple
Mutable (changeable) Yes No
Syntax [ ] square brackets ( ) parentheses
Speed Slower Faster
Memory usage More memory Less memory
Methods available Many (append, remove, sort, etc.) Few (count, index only)
Best use case Data that changes (scores, inventory, players) Fixed data (coordinates, days of week, constants)
# When to use list:
scores = [85, 92, 78]     # scores may change
scores.append(95)          # OK to add new scores

# When to use tuple:
days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")  # fixed
rgb_color = (255, 128, 0)  # fixed color value
player_position = (x, y)   # coordinates that shouldn't change accidentally
Rule of thumb: Use lists for collections that change (like scores or inventory). Use tuples for fixed data (like coordinates or constants).

6. Looping through collections

# For loop with list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# For loop with tuple
colors = ("red", "green", "blue")
for color in colors:
    print(color)

# Loop with index (using range and len)
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# Using enumerate (get both index and value) - BEST way!
for i, fruit in enumerate(fruits):
    print(f"Index {i}: {fruit}")

# List comprehension (create new list from existing) - very powerful!
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]   # [1, 4, 9, 16, 25]
even_numbers = [n for n in numbers if n % 2 == 0]  # [2, 4]

7. Quick reference

# LISTS (mutable - can change)
my_list = [1, 2, 3]           # create
my_list.append(4)             # add to end
my_list.insert(0, 0)          # insert at position
my_list[1] = 10               # change value
my_list.remove(3)             # remove by value
value = my_list.pop()         # remove last
my_list.sort()                # sort ascending
my_list.reverse()             # reverse order
len(my_list)                  # get length
3 in my_list                  # check if exists

# TUPLES (immutable - cannot change)
my_tuple = (1, 2, 3)          # create
my_tuple[1]                   # access (cannot change!)
t1 + t2                       # concatenate (creates new tuple)
t1 * 3                        # repeat
my_tuple.count(2)             # count occurrences
my_tuple.index(2)             # find position
len(my_tuple)                 # get length

# CONVERSIONS
list_to_tuple = tuple(my_list)
tuple_to_list = list(my_tuple)

8. Quick Challenge: Spot the Collection in Our Game

Look at this code from Code-3 (multiple cacti). Can you spot the list and tuple?

# List to store active cacti
active_cacti = []

while True:
    # Spawn a new cactus
    current_time = pygame.time.get_ticks()
    if current_time - last_spawn_time > 1000:
        cactus_rect = cactus_img.get_rect(midbottom=(900, 400))
        active_cacti.append(cactus_rect)   # ADD to list
    
    # Update all cacti
    for cactus_rect in active_cacti:       # LOOP through list
        cactus_rect.x -= 6
    
    # Game over screen
    font = pygame.font.Font(None, 36)
    text = font.render("Press SPACE to start", True, (100, 100, 255))  # RGB tuple!

Questions:

  1. What is the name of the list variable?
  2. What do we use the list for?
  3. Where is the tuple in this code?
  4. Why is the color stored as a tuple?
Click for answers
  1. active_cacti
  2. To store all the cactus rectangles that are currently on screen
  3. (100, 100, 255) - the RGB color value
  4. RGB colors are fixed values that never change, so a tuple is perfect!

9. Exercises

Try these exercises to practice lists and tuples. Write your code in Thonny.

  • Exercise 1: Create fruits = ["apple", "banana", "cherry"]. Append "orange", insert "grape" at position 1. Print result.
  • Exercise 2: Sort numbers = [5, 2, 9, 1, 7, 3] ascending, then reverse. Print both.
  • Exercise 3: Remove first "blue" from ["red","blue","green","blue","yellow"], then count remaining "blue".
  • Exercise 4: Try changing a value in days = ("Mon","Tue","Wed","Thu","Fri"). What happens?
  • Exercise 5: Use list comprehension to get even numbers from 1-10.
  • Exercise 6: Unpack coordinates = (10, 20, 30) into x, y, z and print sum.
  • Exercise 7: Ask user for 5 numbers, store in list, print max, min, average.
  • Exercise 8: From words = ["hello","world","python"], create list of word lengths.
  • Exercise 9: Combine [1,2,3] and [4,5,6] using + and extend().
  • Exercise 10: Remove duplicates from [1,2,2,3,4,4,4,5] without using set().
  • Exercise 11: Create RGB tuples for red, green, blue, and yellow. Print them.

10. Common Errors & Solutions

  • IndexError: list index out of range
    -> You tried to access an index that doesn't exist. Remember indexes go from 0 to len(list)-1.
  • TypeError: 'tuple' object does not support item assignment
    -> You tried to change a tuple! Tuples are immutable. Use a list if you need to change values.
  • AttributeError: 'tuple' object has no attribute 'append'
    -> You can't append to a tuple. Convert to list first: my_list = list(my_tuple).
  • ValueError: list.remove(x): x not in list
    -> You tried to remove an item that doesn't exist in the list. Check with if item in list: first.
  • Single-element tuple confusion
    -> (5) is just the number 5! Use (5,) (with comma) for a single-element tuple.
Debugging tip: Use print(type(variable)) to check if something is a list or tuple. Use len(variable) to see how many items.

11. Check Your Understanding

  1. What is the main difference between a list and a tuple?
  2. How do you access the first element of a list called items?
  3. What method adds an item to the end of a list?
  4. What happens if you try to change an element in a tuple?
  5. How do you convert a list to a tuple?
  6. When should you use a tuple instead of a list?
Click for Answers
  1. Lists are mutable (changeable), tuples are immutable (unchangeable).
  2. items[0] (indexing starts at 0)
  3. append()
  4. You get an error: TypeError: 'tuple' object does not support item assignment
  5. tuple(my_list)
  6. For fixed data that shouldn't change (coordinates, colors, days of week, constants)

12. Your Progress Tracker

Check off each item as you master it:
I can create and use lists
I can add, remove, and modify list items
I understand indexing and slicing
I can sort and reverse lists
I can create and use tuples
I understand that tuples are immutable
I know when to use a list vs a tuple
I can loop through lists and tuples
I can unpack tuples
I completed at least 8 exercises