How to Modify an Item Within a List in Python

Looking to modify an item within a list in Python?

If so, I’ll show you 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, I created a list of names using this syntax:

Names = ['Jon', 'Bill', 'Maria', 'Jenny', 'Jack']
print(Names)

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

Python List

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 do I mean by saying 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 of 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:

How to Modify an Item Within a List in Python

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 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 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:

Modify a List in Python