How to modify an item within a list in Python

Published on Aug. 22, 2023, 12:12 p.m.

Steps to Modify an item within a list in Python.

Step 1: create a List.

To start, create a list .

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

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

Step 2: an Modify Item within the list .

You can modify an item within a list in Python by referring.

Each item within a list has an index number associated with that item.

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

ListName[index of the item to be changed] = New value for the item.

Names[2] = 'Mona'

So the complete Python code to change the third item is:

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

#modify
Names[2] = 'Mona'

print(Names)

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

Change Multiple items within a list .

For example, what if you want to change the last 3 names .

The range of index values where changes are required is 2:5.So here is the code to change the last 3 names .

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

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

print(Names)

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

You can get the same same results by using Names.

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

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

print(Names)