Change List items in Python
Change List Items in Python
In Python, lists are mutable, meaning you can change, add, and remove items after the list has been created. This lesson will cover how to change individual list items, modify ranges of items, and insert new items into a list.
1. Change Item Value
To change the value of a specific item in a list, you can refer to its index number. Remember that Python uses zero-based indexing, so the first item is at index 0
.
Example:
Change the second item in the list:
python
1thislist = ["apple", "banana", "cherry"]
2thislist[1] = "blackcurrant" # Changing "banana" to "blackcurrant"
3print(thislist) # Output: ['apple', 'blackcurrant', 'cherry']
2. Change a Range of Item Values
You can also change the values of items within a specific range. To do this, define a new list with the desired values and specify the range of index numbers you want to change.
Example:
Change the values "banana" and "cherry" to "blackcurrant" and "watermelon":
python
1thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
2thislist[1:3] = ["blackcurrant", "watermelon"]
3print(thislist) # Output: ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
Note on Inserting More Items
If you insert more items than you replace, the new items will be inserted at the specified index, and the remaining items will shift accordingly.
Example:
Change the second value by replacing it with two new values:
python
1thislist = ["apple", "banana", "cherry"]
2thislist[1:2] = ["blackcurrant", "watermelon"]
3print(thislist) # Output: ['apple', 'blackcurrant', 'watermelon', 'cherry']
Note on Inserting Fewer Items
If you insert fewer items than you replace, the new items will still be inserted at the specified index, and the remaining items will adjust accordingly.
Example:
Change the second and third values by replacing them with one value:
python
1thislist = ["apple", "banana", "cherry"]
2thislist[1:3] = ["watermelon"]
3print(thislist) # Output: ['apple', 'watermelon']
3. Insert Items
To add a new item to a list without replacing any existing items, you can use the insert()
method. This method allows you to specify the index at which you want to insert the new item.
Example:
Insert "watermelon" as the third item:
python
1thislist = ["apple", "banana", "cherry"]
2thislist.insert(2, "watermelon") # Inserting "watermelon" at index 2
3print(thislist) # Output: ['apple', 'banana', 'watermelon', 'cherry']