Changing List Items in Python
Lists are mutable, meaning their elements can be changed after they have been created. You can change the value of a specific item by referring to its index number.
Modifying Single Elements
Example: Changing a Single Item
# Changing list items
names = ["Karthick AG", "Durai", "Vijay", "John"]
print("Original List:", names)
names[3] = "Praveen"
print("Modified List:", names)
Output
Original List: ['Karthick AG', 'Durai', 'Vijay', 'John']
Modified List: ['Karthick AG', 'Durai', 'Vijay', 'Praveen']
Explanation: We changed the fourth item (index 3) from "John" to "Praveen" by assigning a new value to names[3]
.
Modifying Multiple Elements
Example: Changing Multiple Items
# Changing multiple list items
numbers = [1, 2, 3, 4, 5, 6]
print("Original List:", numbers)
numbers[1:4] = [20, 30, 40]
print("Modified List:", numbers)
Output
Original List: [1, 2, 3, 4, 5, 6]
Modified List: [1, 20, 30, 40, 5, 6]
Explanation: By assigning a new list to a slice of the original list, we can change multiple items at once.