Table of Contents
ToggleA list is a mutable data type in Python. This means that its contents can be modified in place after the object is stored in memory. You can assign a new value at a given index position in the list.
list1[i] = new_value
You can change the value of a specific item in a list by assigning a new value to its index.
list3 = [1, 2, 3, 4, 5]
print("Original list", list3)
list3[2] = 10
print("List after changing value at index 2:", list3)
Output:
Original list [1, 2, 3, 4, 5]
List after changing value at index 2: [1, 2, 10, 4, 5]
You can replace multiple consecutive items in a list with another sublist.
list1 = ["a", "b", "c", "d"]
print("Original list:", list1)
list2 = ['Y', 'Z']
list1[1:3] = list2
print("List after changing with sublist:", list1)
Output:
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Y', 'Z', 'd']
If the replacement sublist has more items than the slice being replaced, the extra items will be inserted.
list1 = ["a", "b", "c", "d"]
print("Original list:", list1)
list2 = ['X', 'Y', 'Z']
list1[1:3] = list2
print("List after changing with sublist:", list1)
Output:
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']
If the sublist used for replacement has fewer items than the slice being replaced, the extra items in the original list will be removed.
list1 = ["a", "b", "c", "d"]
print("Original list:", list1)
list2 = ['Z']
list1[1:3] = list2
print("List after changing with sublist:", list1)
Output:
Original list: ['a', 'b', 'c', 'd']
List after changing with sublist: ['a', 'Z', 'd']
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now