From the course: Programming Foundations: Data Structures (2023)

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Mutate a list in Python

Mutate a list in Python

- [Instructor] Sometimes you'll want to modify or update the data in your array-like structure. For example, let's say a neighbor's dog had babies and they gave away six of them to students. This means the values in our student pet count list need to change. We'll say one student got three new dogs, another student got one cat, and the last got two new dogs. Modifying an item in a list is very similar to accessing an item. We use the list name, square brackets, and the index to designate which entry we want to modify. We'll modify the item at index two to be three. This means one of the students that had zero pets before now has three pets. We'll also do this with the item at index three. We'll say they got one more pet. Now what we have here would not give us what we expect. We changed the value of the item at index three to be one, but before, it had the value two. Since we're adding a new pet to this family, we'll want…

Contents