How to update values in a List in Python?

In Python, lists are mutable. It means we can change the list’s contents by adding, updating, or removing elements from the list. In this article, we will discuss how to do update values of existing list elements in Python.

Updating existing element in the list

The list is an index-based sequential data structure. Therefore we can access list elements by their index position and change their values. Let’s understand by an example,

Suppose we have a list of numbers,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

Now we want to change the value of the 3rd element from 11 to 21.
We need to access the 3rd element from the list using square brackets and the index position of the element. Then assign a new value to it. Like this,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

# Update value of 3rd element in list
list_of_numbers[2] = 21

print(list_of_numbers)

Output:

[9, 10, 21, 12, 13, 14, 15]

As indexing starts from 0 in list, so index position of third element in list is 2. We accessed the element at index position two and assigned a new value to it.

Updating multiple elements in a list

You can select multiple items from a list using index range, i.e., start & end index positions. For example,

list_obj[start : end]

It returns a reference to the selected elements from the calling list object, and we can assign new values to these elements. Let’s see an example,

Suppose we have a list of numbers,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

Now we want to change the value of the first three elements to 10. For that we can select a range from list i.e., from index position 0 to 3 and assign value 10 to it,

list_of_numbers = [9, 10, 11, 12, 13, 14, 15]

# change the value of the first three elements to 10.
list_of_numbers[0:3] = [10, 10, 10]

print(list_of_numbers)

Output:

[10, 10, 10, 12, 13, 14, 15]

It updated the value of the first three elements in the list.

Summary:

Today we learned how to update values of single or multiple elements in a list.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top