深度阅读

How to modify an item within a list in Python

作者
作者
2023年08月22日
更新时间
14.76 分钟
阅读时间
0
阅读量

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)

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。