- Use index assignment
list[i] = new_valueto change an item at a specific position. - Define "method" as a function that belongs to an object.
- Use the
.append()list method to add a new item to the end of a list.
Making Your Lists Dynamic
One of the most powerful features of a Python list is that it is mutable, which is a fancy word for "changeable." You can modify items that are already in the list, or add brand new items to it.
Changing an Item at a Specific Index
If you want to change an item, you can use its index combined with the assignment operator (=). This is just like reassigning a regular variable.
# Let's start with a list of heroes
heroes = ["Batman", "Superman", "Wonder Woman"]
print(f"Original list: {heroes}")
# Let's replace "Superman" at index 1 with "Spider-Man"
heroes[1] = "Spider-Man"
print(f"Modified list: {heroes}")
# Output: Modified list: ['Batman', 'Spider-Man', 'Wonder Woman']
Adding a New Item with .append()
What if you want to add a new item without replacing an old one? For this, we use a method. A method is like a function that "belongs" to a specific object (in this case, our list). The most common list method is .append(), which adds a new item to the very end of the list.
# Let's start with our list again
heroes = ["Batman", "Spider-Man", "Wonder Woman"]
# Now, let's append "The Flash" to the end
heroes.append("The Flash")
print(f"Appended list: {heroes}")
# Output: Appended list: ['Batman', 'Spider-Man', 'Wonder Woman', 'The Flash']
Knowledge Check: Predict the Result!
Let's see if you can predict how a list will change. Try the interactive activity below to test your skills.
Live Example: Building a Shopping List
This Trinket demonstrates both modifying and appending items in the context of a simple shopping list. Run it, then follow the "Your Turn" instructions to practice using these powerful tools yourself!
The skills you learned today—especially .append()—are the absolute core of the "List Manager" project. You will use this method to allow the user to add new items to their to-do list or shopping list.
Interactive Sandbox
Use this space to practice writing code and complete the "Your Turn" activities above.