In Python, lists are mutable, which means you can change their items after the list is created. You can update a single item using its index, replace a slice (range) of items, insert new items at any position, and even change the overall length of the list using slice assignment.
insert() adds a new item at a specific position without overwriting existing items.Use the index (starting from 0) to update a specific element in the list.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']
Use slicing to replace multiple items at once. The slice [start:end] includes indices from start up to end - 1.
numbers = [1, 2, 3, 4, 5]
numbers[1:3] = [20, 30]
print(numbers) # [1, 20, 30, 4, 5]
insert()Use insert(index, value) to add a new item at a specific position without removing any existing items.
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits) # ['apple', 'orange', 'banana', 'cherry']
Slice assignment can insert more or fewer items than the slice length, which changes the overall size of the list.
letters = ["a", "b", "c", "d"]
letters[1:3] = ["x", "y", "z"]
print(letters) # ['a', 'x', 'y', 'z', 'd']
fruits[1] = "mango" replaces only the item at index 1 ("banana" becomes "mango").numbers[1:3] = [20, 30] replaces the items at indices 1 and 2 (2, 3) with 20, 30.fruits.insert(1, "orange") adds "orange" at index 1 and shifts the rest to the right.letters[1:3] = ["x", "y", "z"] replaces "b", "c" with three items, so the list grows by one element.This shows how flexible Python lists are: you can carefully control what changes and where it changes using indices, slices, and methods like insert().
insert() when you want to add without overwriting existing items."lion"."grape" at index 2 in a fruit list using insert().