Change List Items

 

What You'll Learn: In this tutorial, you'll discover how to change the value of items in a list using their index numbers. Think of it like swapping ingredients in a recipe!

Change a Specific Item

To change the value of a specific item, refer to its index number.

Example Code:

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

Output: ['apple', 'blackcurrant', 'cherry']
 

What's Happening Here?

  • thislist[1] = "blackcurrant" changes the second item from 'banana' to 'blackcurrant'.

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values and refer to the range of index numbers.

Example Code:

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

Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
 

What's Happening Here?

  • thislist[1:3] changes 'banana' and 'cherry' to 'blackcurrant' and 'watermelon'.

Inserting More or Less Items

If you insert more items than you replace, the new items will be inserted where specified, and the rest will move accordingly.

Example Code:

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

Output: ['apple', 'blackcurrant', 'watermelon', 'cherry']
 

If you insert fewer items than you replace, the list adjusts accordingly.

Example Code:

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

Output: ['apple', 'watermelon']
 

Insert Items Without Replacing

To insert a new item without replacing any existing values, use the insert() method.

Example Code:

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

Output: ['apple', 'banana', 'watermelon', 'cherry']
 

What's Happening Here?

  • thislist.insert(2, "watermelon") inserts 'watermelon' at the third position.

Try It Yourself: Fun Exercises

  1. Update Your Snack List:
    • Create a list of snacks.
    • Change one snack to another using its index.
  2. Revamp Your Playlist:
    • Create a list of favorite songs.
    • Replace two songs with new ones using a range of indexes.

Summary:

In this Python tutorial, we learned how to change item values in a list using their index numbers, including changing specific items, ranges, and inserting new items without replacing. Lists are versatile and allow you to update and organize items easily. Keep experimenting and have fun with lists in Python!