Skip to content

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 index
my_list = [10, 20, 30, 40]
my_list[1] = 25 # Updates the second element to 25
# Adding elements
my_list.append(50) # Adds 50 to the end
my_list.insert(2, 35) # Inserts 35 at index 2
# Removing elements
my_list.remove(25) # Removes the first occurrence of 25
my_list.pop(3) # Removes the element at index 3

Example

# Modifying a list of fruits
fruits = ["apple", "banana", "cherry"]
# Updating an element
fruits[1] = "blueberry"
print(f"Updated list: {fruits}")
# Adding new elements
fruits.append("date")
print(f"After adding a fruit: {fruits}")
# Removing an element
fruits.remove("apple")
print(f"After removing a fruit: {fruits}")