Learn How to modify list elements in Python List
In this tutorial, you will learn how to modify the list elements in Python List.
In python 3, we use the index number of the list element to modify individual list elements. Remember that Python lists start with the index position
1. The first element of the list has the index position
0, while the second element has the index position
We use the following syntax to modify a list item in python programming. To change a list element we use the list name followed by the index position inside the square brackets (), and then provide the new value using the equal sign.
list_name[index_position] = "New Value"
In the above example, we have a python list called languages which contains the list of programming languages. Next, we replace the index
0 of the list (first item), which is Perl, with the new value “Python 3” (“Perl” will be replaced by “Python 3”).
The above code will output the following:
Also, remember that Python lists support negative indexes.
-1 is always the last element of the list,
-2 is the second-to-last element, and so on.
In example 2, we use the same language list. But this time, we modify index
2 of the list, which is the third element of the list (the third element, which is “Java”, will be replaced by “Python 3”).
The above Python code will output the following:
As you can see, modifying or replacing an element in a python list is simple.