Python List Elements

Modify Python List Elements: Insert, Replace & Update Values








Modify Python List Elements: Insert, Replace & Update Values

How to Change Items in a Python List

In Python, lists are mutable, which means their elements can be changed after the list has been created. This tutorial from Devyra provides a comprehensive explanation on how to modify list items by using index positions, ranges, and insertion methods.

Change the Value of a Specific Item

To update a specific item in a list, refer to its index number. Indexing in Python starts at 0.

thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values

You can modify multiple items at once by specifying a range and assigning new values to it. Python will replace the values within that range accordingly.

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

Insert More Items Than Replaced

If you replace fewer items with more, the list will expand to accommodate the new values.

thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Insert Fewer Items Than Replaced

Likewise, if you insert fewer items than you replace, the list will shrink accordingly.

thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items Without Replacing

To add a new item at a specific index without replacing any existing elements, use the insert() method.

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

This guide has been curated by Devyra, your go-to source for clear, concise Python tutorials.


More From Author

Accessing List

Accessing List Items in Python

Add Items to a List

How to Add Items to a List in Python – Append, Insert, Extend

Leave a Reply

Your email address will not be published. Required fields are marked *