Skip to main content

Change Item Value

To give one item a new value, assign to it using its index number:

Example

Replace the second item with "blackcurrant":

Prompt
Create a list of fruits and change the second item to "blackcurrant". Print the list.
Output: complete Python program

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":

Prompt
Create a list of six fruits. Change the second and third items to "blackcurrant" and "watermelon" using a range of indexes. Print the list.
Output: complete Python program

Example

Put two new values in place of the second item:

Prompt
Create a list of three fruits. Replace the second item with two new values "blackcurrant" and "watermelon" using a range. Print the list.
Output: complete Python program

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.

Prompt
Create a list of three fruits. Replace the second and third items with one value "watermelon" using a range. Print the list.
Output: complete Python program

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:

Prompt
Create a list of three fruits. Use the insert() method to add "watermelon" as the third item. Print the list.
Output: complete Python program