Python – Change List Items
In Python, lists are mutable, which means their contents (items) can be changed after creation. You can:
- Change individual items
- Change multiple items using slicing
- Increase or decrease list size during replacement
- Use loops or conditions to modify values
1. Change a Single Item in a List
Use the index to replace a specific item.
Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits)
Output:
['apple', 'mango', 'cherry']
Indexing starts at 0.
2. Change Multiple Items (Using Slicing)
You can change several items at once using slicing.
Example:
fruits = ["apple", "banana", "cherry", "orange"]
fruits[1:3] = ["kiwi", "pineapple"]
print(fruits)
Output:
['apple', 'kiwi', 'pineapple', 'orange']
3. Replace with Fewer Items Than Selected
You can shrink the list by replacing more items with fewer.
Example:
fruits = ["apple", "banana", "cherry", "orange"]
fruits[1:3] = ["grape"]
print(fruits)
Output:
['apple', 'grape', 'orange']
4. Replace with More Items Than Selected
You can increase the list size if you assign more values than selected.
Example:
fruits = ["apple", "banana", "cherry"]
fruits[1:2] = ["blackberry", "pear", "kiwi"]
print(fruits)
Output:
['apple', 'blackberry', 'pear', 'kiwi', 'cherry']
5. Replace All Items in a List
To completely overwrite the contents of a list:
Example:
fruits = ["apple", "banana", "cherry"]
fruits[:] = ["orange", "mango", "kiwi"]
print(fruits)
Output:
['orange', 'mango', 'kiwi']
6. Use a Loop to Modify Items
You can apply transformations to all elements using a loop.
Example: Multiply all elements by 2
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] *= 2
print(numbers)
Output:
[2, 4, 6, 8, 10]
7. Conditional Changes in a Loop
Modify list items based on conditions.
Example: Replace odd numbers with "odd"
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
if numbers[i] % 2 != 0:
numbers[i] = "odd"
print(numbers)
Output:
['odd', 2, 'odd', 4, 'odd']
8. Change Nested List Items
Python lists can contain other lists (nested lists), and you can access and modify them too.
Example:
nested = [["a", "b"], ["c", "d"]]
nested[1][0] = "x"
print(nested)
Output:
[['a', 'b'], ['x', 'd']]
⚠️ Common Mistakes to Avoid
Mistake | Why it's wrong |
---|---|
fruits[3] = "kiwi" | IndexError if list has fewer than 4 items |
fruits[1:3] = "kiwi" | Will split "kiwi" into ['k', 'i', 'w', 'i'] |
Correct Way:
fruits[1:3] = ["kiwi"]
Summary
- Use indexing (
list[i]
) to change individual items - Use slicing (
list[start:end]
) for multiple items - Replacing can change the size of the list
- You can also use loops and conditions to modify values
- Be careful when replacing using a string—it behaves like a list of characters