Mingming Li — Click any blue heading below to expand the content.
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 [ ].
# 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)
# 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!")
A tuple is similar to a list, but it is immutable (cannot be changed after creation). Tuples are created using parentheses ( ).
# 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
# 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
| 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
# 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]
# 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)
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:
active_cacti(100, 100, 255) - the RGB color valueTry these exercises to practice lists and tuples. Write your code in Thonny.
fruits = ["apple", "banana", "cherry"]. Append "orange", insert "grape" at position 1. Print result.numbers = [5, 2, 9, 1, 7, 3] ascending, then reverse. Print both.["red","blue","green","blue","yellow"], then count remaining "blue".days = ("Mon","Tue","Wed","Thu","Fri"). What happens?coordinates = (10, 20, 30) into x, y, z and print sum.words = ["hello","world","python"], create list of word lengths.[1,2,3] and [4,5,6] using + and extend().[1,2,2,3,4,4,4,5] without using set().my_list = list(my_tuple).if item in list: first.(5) is just the number 5! Use (5,) (with comma) for a single-element tuple.print(type(variable)) to check if something is a list or tuple. Use len(variable) to see how many items.
items?items[0] (indexing starts at 0)append()tuple(my_list)