Python 3 — Managing Sequences with Lists & Tuples
So far, we have only stored single items in variables. But what if you have a list of user emails, a list of prices, or high scores? Python lists and tuples allow you to store multiple items in a single variable.
A list is an ordered, changeable (mutable) collection of elements wrapped in square brackets ([]). You can add, remove, and modify items in a list:
fruits = ["Apple", "Banana", "Cherry"]
# Modifying an item
fruits[1] = "Blueberry"
# Appending a new item to the end
fruits.append("Orange")
# Removing an item
fruits.remove("Apple")
print(fruits) # ['Blueberry', 'Cherry', 'Orange']
print(len(fruits)) # 3 (size of list)
To loop through every item in a list, pair it with a for loop. This reads naturally like English:
languages = ["Python", "Java", "Go", "Rust"]
for lang in languages:
print(f"I can compile {lang} code!")
A tuple is similar to a list, but with one key difference: **once created, it can never be changed**. Tuples are written with parentheses (()) and are safer for data that should remain constant (like latitude/longitude coordinates):
dimensions = (1920, 1080)
# This would crash: dimensions[0] = 1280
print(dimensions[0]) # 1920
If your list has 3 items and you try to access my_list[3], Python will throw an IndexError: list index out of range. Remember, indexing starts at 0, so a list of size 3 only has indices 0, 1, and 2!
Create a list containing five of your favorite songs. Append a new song to the end, print the length of the list, and use a loop to display each song title in uppercase letters.