Learn How to modify list elements in Python List

In this tutorial we are going to 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 list starts with the index position 0 not 1. First element of the list has the index position 0, while the second element of the list has the index position 1.

We use following syntax to modify a list item in python programming. To change a list element we use, list name followed by the index position inside the square brackets ([]), and then provides the new value using the Equal sign.

list_name[index_position] = "New Value"

 

Example 1

languages = ["Perl", "PHP", "Java", "C", "JavaScript", "C++"]
print(languages)

languages[0] = "Python 3"
print(languages)

In the above example we have a python list called languages which contains the list of some programming languages. Next, we replace the index 0 of the list(First element) which is Perl with the new value "Python 3" (So the "Perl" will replace by "Python 3"). The above code will output.

['Perl', 'PHP', 'Java', 'C', 'JavaScript', 'C++']

['Python 3', 'PHP', 'Java', 'C', 'JavaScript', 'C++']

 

Example 2

languages = ["Perl", "PHP", "Java", "C", "JavaScript", "C++"]
print(languages)

languages [2] = "Python 3"
print(languages)

In the example 2, we use the same language list, But this time we modify the index 2 of the list, which is the third element of the list (So the third element "Java" will replace by "Python 3"). The above python code will output.

['Perl', 'PHP', 'Java', 'C', 'JavaScript', 'C++']

['Perl', 'PHP', 'Python 3', 'C', 'JavaScript', 'C++']

So you can see modifying or replacing an element in python list is very easy and straightforward.