Change Item Value
To give one item a new value, assign to it using its index number:
Example
Replace the second item with "blackcurrant":
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Change a Range of Item Values
You can also replace several items in a row. Write a list of new values, then assign it to the range of indexes those values should fill:
Example
Swap "banana" and "cherry" for "blackcurrant" and "watermelon":
Output: complete Python program
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Example
Put two new values in place of the second item:
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
Example
Put one new value in place of the second and third items:
Note: If you insert more or fewer items than you replace, the list grows or shrinks to match.
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)
Insert Items
Sometimes you want a new item without overwriting anything. That is what the insert() method is for.
It takes an index and places the item at that position:
Note: After this example runs, the list holds 4 items.
Example
Make "watermelon" the third item, pushing "cherry" back one place:
Output: complete Python program
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)