Modify an Item Within a List in Python

To modify an item within a list in Python:

list_name[Index of the item to be modified] = "New value for the item"

Where the index of the first item in the list is zero, and then increases sequentially.

Steps to Modify an Item Within a List in Python

Step 1: Create a List

To start, create a list in Python. For example:

list_names = ["Jon", "Bill", "Maria", "Jenny", "Jack"]

print(list_names)

Run the code in Python, and you’ll get this list:

['Jon', 'Bill', 'Maria', 'Jenny', 'Jack']

Step 2: Modify an Item within the list

For example, to modify the third item (index of 2) in the list from “Maria” to “Mona“:

list_names[2] = "Mona"

So the complete Python code to change the third item from Maria to Mona is:

list_names = ["Jon", "Bill", "Maria", "Jenny", "Jack"]

list_names[2] = "Mona"

print(list_names)

Notice that the third item changed from Maria to Mona:

['Jon', 'Bill', 'Mona', 'Jenny', 'Jack']

Change Multiple Items Within a List

What if you want to change multiple items within your list?

For instance, to change the last 3 names in the original list:

  • From “Maria” to “Mona”
  • From “Jenny” to “Lina”
  • From “Jack” to “Mark”

In that case, specify the range of index (range of 2:5) to change the last 3 names in the list:

list_names = ["Jon", "Bill", "Maria", "Jenny", "Jack"]

list_names[2:5] = "Mona", "Lina", "Mark"

print(list_names)

You’ll now see the updated list with the 3 new names:

['Jon', 'Bill', 'Mona', 'Lina', 'Mark']

You can get the same same results using list_names[-3:]:

list_names = ["Jon", "Bill", "Maria", "Jenny", "Jack"]

list_names[-3:] = "Mona", "Lina", "Mark"

print(list_names)

And as before, you’ll now see the updated list with the 3 new names:

['Jon', 'Bill', 'Mona', 'Lina', 'Mark']

Leave a Comment