How to Change List Items in Python: Update and Modify Values
Discover how to modify specific items in a Python list by changing their values using their index number. Learn the basics of updating list elements with practical examples and code snippets, including how to replace an item and print the updated list.
Python - Change List Items
Change Item Value
To change the value of a specific item in a list, refer to its index number:
Example
thislist = ["orange", "grape", "melon"]
thislist[1] = "blueberry"
print(thislist)
Output
['orange', 'blueberry', 'melon']
Change a Range of Item Values
To change multiple items within a specific range, define a list with the new values and refer to the range of index numbers where you want to insert the new values:
Example
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Output
['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
If you insert more items than you replace, the new items will be inserted at the specified location, and the remaining items will shift accordingly:
Example
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
Output
['apple', 'blackcurrant', 'watermelon', 'cherry']
Note: The length of the list will change if the number of items inserted does not match the number of items replaced.
If you insert fewer items than you replace, the new items will be inserted at the specified location, and the remaining items will shift accordingly:
Example
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Output
['apple', 'watermelon']
Insert Items
To insert a new item into a list without replacing any of the existing
values, use the insert()
method. This method inserts an
item at the specified index:
Example
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
Output
['apple', 'banana', 'watermelon', 'cherry']
Note: As a result of the above example, the list now contains 4 items.