Python Update Lists
Syntax
You can update lists in Python by assigning new values to elements or using methods like append(), insert(), and extend().
# Updating elements by indexmy_list = [10, 20, 30, 40]my_list[1] = 25 # Updates the second element to 25
# Adding elementsmy_list.append(50) # Adds 50 to the endmy_list.insert(2, 35) # Inserts 35 at index 2
# Removing elementsmy_list.remove(25) # Removes the first occurrence of 25my_list.pop(3) # Removes the element at index 3Example
# Modifying a list of fruitsfruits = ["apple", "banana", "cherry"]
# Updating an elementfruits[1] = "blueberry"print(f"Updated list: {fruits}")
# Adding new elementsfruits.append("date")print(f"After adding a fruit: {fruits}")
# Removing an elementfruits.remove("apple")print(f"After removing a fruit: {fruits}")