MWZ

MINDWAREZONE

Updating List Items in python

Lists in Python are mutable, which means you can change, replace, or update their items after the list has been created. This makes lists a flexible data structure for storing and managing data.

In this tutorial, you'll learn how to update a single item and multiple items in a Python list.

Change a Single Item

To update a single item in a list, use its index number and assign a new value.

Syntax

list_name[index] = new_value
            

Example

fruits = ["Apple", "Banana", "Mango"] 
fruits[1] = "Orange" 
print(fruits)
            

Output:

['Apple', 'Orange', 'Mango']
            

In this example, the item at index 1 ("Banana") is replaced with "Orange".

Change Multiple Items

You can update multiple items at once by specifying a range of indexes and assigning a new list of values.

Syntax

list_name[start:end] = [new_values]
            

Example

fruits = ["Apple", "Banana", "Mango", "Grapes"] 
fruits[1:3] = ["Orange", "Pineapple"] 
print(fruits)
            

Output:

['Apple', 'Orange', 'Pineapple', 'Grapes']
            

The items from index 1 to 2 are replaced with the new values.

Method Description
list[index] = value Updates a single item
list[start:end] = [...] Updates multiple items
Slice assignment Can add or remove items while updating