How to Change a Value in a List in Python
To change a value in a list in Python, you can use indexing or the insert() function along with the pop() function.
The following examples show how to change a value in a list.
Using Indexing
We can use indexing to change a value in a list.
Suppose we have the following list:
# Declare list
list1 = ["A", "B", "C", "D"]
# Change value in the list
list1[2] = "Z"
# Show updated list
print("Updated list:", list1)
Output: 👇️
Updated list: ['A', 'B', 'Z', 'D']
In this example, we change the value at index 2 to “Z” and show the updated list.
Using insert() & pop() Functions
We can use the insert() and pop() functions to change a value in a list.
Suppose we have the following list:
# Declare list
list1 = ["A", "B", "C", "D"]
# Change value in the list
list1.pop(0)
list1.insert(0, "a")
# Show updated list
print("Updated list:", list1)
Output: 👇️
Updated list: ['a', 'B', 'C', 'D']
In this example, we first remove the value at index 0 using the pop() function and then insert the new value “a” at index 0 using the insert() function.
Conclusion
We can use indexing and the insert() and pop() functions to change a value in a list.