How to Modify an Item Within a List in Python

Looking to modify an item within a list in Python?

If so, you’ll see the steps to accomplish this goal using a simple example.

Steps to Modify an Item Within a List in Python

Step 1: Create a List

To start, create a list in Python. For demonstration purposes, the following list of names will be created:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack']
print(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

You can modify an item within a list in Python by referring to the item’s index.

What does it mean an “item’s index”?

Each item within a list has an index number associated with that item (starting from zero). So the first item has an index of 0, the second item has an index of 1, the third item has an index of 2, and so on.

In our example:

  • The first item in the list is ‘Jon.’ This item has an index of 0
  • ‘Bill’ has an index of 1
  • ‘Maria’ has an index of 2
  • ‘Jenny’ has an index of 3
  • ‘Jack’ has an index of 4

Let’s say that you want to change the third item in the list from ‘Maria’ to ‘Mona.’ In that case, the third item in the list has an index of 2.

You can then use this template to modify an item within a list in Python:

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

And for our example, you’ll need to add this syntax:

Names[2] = 'Mona'

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

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

#modify
Names[2] = 'Mona'

print(Names)

When you run the code, you’ll get the modified list with the new name:

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

Change Multiple Items Within a List

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

For example, what if you want to change the last 3 names in the original list:

  • From ‘Maria’ to ‘Mona’
  • From ‘Jenny’ to ‘Lina’
  • From ‘Jack’ to ‘Mark’

You can then specify the range of index values where the changes are required. For our example, the range of index values where changes are required is 2:5. So here is the code to change the last 3 names in the list:

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

#modify
Names[2:5] = 'Mona','Lina','Mark'

print(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 by using Names[-3:] as below:

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

#modify
Names[-3:] = 'Mona','Lina','Mark'

print(Names)

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

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