- Home
- /
- Python Change List Items
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Change List Items
Python Change List Items
In Python, changing elements inside a list is simple. Since lists are mutable (meaning we can modify them), you can update any value just by using its index.
Change a Single Item
You can directly assign a new value to a specific index.
players = ["Ali", "Fatima", "Sara", "Omar", "Zain"]
players[2] = "Laiba"
print(players)
Output:
['Ali', 'Fatima', 'Laiba', 'Omar', 'Zain']
Here, "Sara"
at index 2
is replaced with "Laiba"
.
Change Multiple Items at Once
You can also change multiple values by giving a range of indexes and assigning new values.
players = ["Ali", "Fatima", "Sara", "Omar", "Zain"]
players[1:3] = ["Hassan", "Areeba"]
print(players)
Output:
['Ali', 'Hassan', 'Areeba', 'Omar', 'Zain']
In this example, "Fatima"
and "Sara"
were replaced by "Hassan"
and "Areeba"
.
What If You Give Fewer New Values Than the Range?
Python will remove everything in the range and only insert the given values.
players = ["Ali", "Fatima", "Sara", "Omar", "Zain"]
players[1:4] = ["Areeba", "Talha"]
print(players)
Output:
['Ali', 'Areeba', 'Talha', 'Zain']
"Fatima"
, "Sara"
, and "Omar"
were all replaced, but we only gave two new names — so Python just adjusted the list.
What If You Give More Values Than the Index Range?
No problem! Python will insert all your values and shift the rest of the list to the right.
players = ["Ali", "Fatima", "Sara", "Omar", "Zain"]
players[2:3] = ["Iqra", "Nashit", "Hadi", "Rabia"]
print(players)
Output:
['Ali', 'Fatima', 'Iqra', 'Nashit', 'Hadi', 'Rabia', 'Omar', 'Zain']
Here, only "Sara"
was selected for replacement, but four new names were added in its place.
Final Tip
Whenever you change multiple items:
The left index is included.
The right index is excluded.
The list automatically adjusts in size.
With this flexibility, lists in Python give you full control over your data.