Change List Items
Lists in Python are mutable, which means you can change, update, or replace items after the list is created.
This makes lists extremely flexible for real-world data manipulation.
This topic covers all valid ways to change list items, from simple updates to advanced slicing techniques.
Change a Single List Item
You can change a specific item by referring to its index number.
python
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits)
python
numbers = [10, 20, 30]
numbers[0] = 100
print(numbers)
Change a Range of List Items (Slicing)
You can replace multiple items at once using slicing.
python
numbers = [1, 2, 3, 4, 5]
numbers[1:3] = [20, 30]
print(numbers)
python
colors = ["red", "green", "blue"]
colors[0:2] = ["yellow", "pink"]
print(colors)
Change List Size While Replacing
The number of new items does not have to match the number being replaced.
Replace with More Items
python
numbers = [1, 2, 3]
numbers[1:2] = [20, 30, 40]
print(numbers)
Replace with Fewer Items
python
numbers = [1, 2, 3, 4]
numbers[1:4] = [99]
print(numbers)
Change Items Using Negative Indexes
python
colors = ["red", "green", "blue"]
colors[-1] = "black"
print(colors)
python
numbers = [10, 20, 30]
numbers[-2] = 200
print(numbers)
Change Items Using Loops
Using Index Loop
python
numbers = [1, 2, 3, 4]
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
print(numbers)
Using Conditional Logic
python
numbers = [10, 15, 20, 25]
for i in range(len(numbers)):
if numbers[i] > 15:
numbers[i] = 0
print(numbers)
Change Nested List Items
Lists can contain other lists.
python
matrix = [
[1, 2],
[3, 4]
]
matrix[0][1] = 20
print(matrix)
python
matrix[1][0] = 30
print(matrix)
Change List Items Using List Comprehension
python
numbers = [1, 2, 3, 4]
numbers = [x * 10 for x in numbers]
print(numbers)
python
values = [5, 10, 15]
values = [x if x > 10 else 0 for x in values]
print(values)
Common Mistakes
Assigning to an Out-of-Range Index
python
numbers = [1, 2, 3]
# numbers[5] = 10 # Error
This raises:
text
IndexError
Forgetting That Slicing Replaces
python
numbers = [1, 2, 3, 4]
numbers[1:3] = [99]
print(numbers)
The list size changes.
Key Difference: Change vs Add
- Changing requires the index to exist
- Adding creates new items
python
numbers = [1, 2, 3]
numbers[3:3] = [4]
print(numbers)
Summary
- Lists are mutable
- Items can be changed using index or slicing
- Slicing can replace multiple items
- List size can change during replacement
- Nested lists require double indexing
- List comprehension is a clean way to modify items
- Invalid index access raises errors
This topic prepares you for:
- Add List Items
- Remove List Items
- List Comprehensions
- Real-world list transformations