In Python, elements in a list can be updated or replaced by assigning a new value to an element’s index position.
In previous articles, we covered accessing list elements by index, using the list index method to find an element’s index, and appending elements to a list. This article focuses on how to update elements in a Python list.
Update List Elements
There is no specific method required to update an element in the list. We can access an element using the index position and assign a new value at that index to update (replace) the element.
Now, let’s see how we can do this in this program.
Program – Update List Elements
# update elements in list
shbytes_list = ['Python', 'AWS', 'Java', 'Azure']
print(shbytes_list)
shbytes_list[2] = 'Machine Learning'
print(shbytes_list)
In this program, we have declared and initialized a list, which is referenced by the variable name sybytes_list
. Element Java
is present at index position 2
. We are assigning a new value Machine Learning
at index 2
, which will update (replace) the previous value at index 2
.
Output – Example Program – Update List Elements
['Python', 'AWS', 'Java', 'Azure']
['Python', 'AWS', 'Machine Learning', 'Azure']
In this example, the original list contains Java
at index 2
. After assigning a new value Machine Learning
to that position, the list reflects the updated element.
Program – Update List Elements in Nested List
# Update List Elements in Nested List
nested_list = ['Python', 'AWS', 'Azure', [1, 2, 3]]
print("original nested list", nested_list)
nested_list[3][2] = 4
print("updated mixed list", nested_list)
We have declared and initialized a nested list, which is referenced by the variable name nested_list
. The nested element [1, 2, 3]
is at index 3
of the list. We are accessing index 3
, which contains the nested list [1, 2, 3]
. Then, we access index 2
of that nested list and assign its value to 4
.
Note: only mutable elements of nested list can be updated. We cannot update immutable elements of a nested list.
Output – Example Program – Update Elements in Nested List
original nested list ['Python', 'AWS', 'Azure', [1, 2, 3]]
updated mixed list ['Python', 'AWS', 'Azure', [1, 2, 4]]
In the output, the last element 3
is replaced with 4
in the nested list.
Summary
This article explains how to modify elements within a Python list by accessing and reassigning values at specific index positions. We explored:
- Update List Elements by index
- Update List Elements in Nested List
Code snippets and programs related to Modify Elements in Python List, can be accessed from GitHub Repository. This GitHub repository all contains programs related to other topics in Python tutorial.
Interview Questions & Answers
Q: How to replace multiple elements in a list?
We can replace multiple elements in a list by assigning a slice of the list to a new list.
number_list = [10, 20, 30, 40, 50]
number_list[1:4] = [200, 300, 400]
print(number_list) # Final number_list elements: [10, 200, 300, 400, 50]
Here, the elements from index 1
to 3
(i.e., 20
, 30
, and 40
) are replaced with 200
, 300
, and 400
respectively.
Q: How can we replace all occurrences of a specific element value in a list?
There are two ways, we can replace all occurrences of a specific element in a list.
- use a list comprehension to create a new list with the replacements
- use a loop with condition to update the element in the same list or create a new list
number_list = [10, 20, 30, 20, 40]
for index in range(len(number_list)):
if number_list[index] == 20:
number_list[index] = 100
print(number_list) # Final elements in number_list: [10, 100, 30, 100, 40]
In this program, we have replaced all occurrences of 20 with 100 in the same number_list
.
Q: If a list contains mixed data types (e.g., integers, strings), how can we replace elements without causing errors?
We need to ensure that the condition checks or replacements are type-safe, meaning they account for different data types to avoid errors:
mixed_list = [10, '20', 30, 'forty']
# Replace only integers equal to 10
for index in range(len(mixed_list)):
if isinstance(mixed_list[index], int) and mixed_list[index] == 10:
mixed_list[index] = 100
print(mixed_list) # Final elements in mixed_list: [100, '20', 30, 'forty']
Here, isinstance(mixed[index], int)
checks if the element is an integer before attempting it to compare with an integer value and replace it with another value.
Test Your Knowledge: Practice Quiz
Related Topics
- Count & Sort Methods in Python Lists: Tutorial with ExamplesThe count() & Sort() methods are built-in methods in Python lists, useful for counting occurrences of elements and sorting of elements in the list. Lists in Python can store duplicate elements and elements of various data types, making these methods essential for data handling. In previous article, we learned about Loops and List Comprehension in Python.…
- Loops and List Comprehension in Python: A Complete GuideLooping is a process to repeat the same task multiple times. It provides sequential access to elements in the list. Comprehension offers a shorter syntax to iterate (loop) through list elements. In previous article, we learned about How to Unpack List in Python. In this article we will learn about Python list loops and List…
- How to Unpack List in Python – Packing and Unpacking in Python (with Programs)Packing & unpacking are two processes that we can perform on lists in Python. We have seen the packing process in our previous article Concatenate Lists in Python, where we used packing to concatenate multiple list elements into a single list. In this article, we will learn in depth about How to Unpack a List…
- Concatenate Lists in Python – Complete Guide to List Concatenation MethodsConcatenation of lists in Python refers to merging of elements from two or more lists into a single list. Python provides a variety of methods for list concatenation, allowing flexibility based on the requirements of each task. For all topics related to lists, check out the Lists in Python: A Comprehensive Guide guide. In the…
- Introduction to List Slicing in Python – Methods, Syntax, and ExamplesList slicing in Python or slicing of list in Python means extracting a part (or slice) of the list. Slicing of list uses the index position of elements in the list. Slicing can be done using either of two methods: In previous articles, we learned about accessing list elements by index, using the list index method to…