How to modify multiple element in python list
If we want to change multiple elements in list at one time we use : operator.
Example for modify multiple element in python list
#1 Example :-
list1 = [ 1, 2, 3, 4, 5 ]
list1[ 2 : 4 ] = [ 10, 20, 30 ]
print( list1 )
Output
[ 1, 2, 10, 20, 30, 5 ]
Note :- Here we can see that we have replaced three elements in list. The only thing we have to remember is that in list1[2 : 4], 2 is indexing and 4 is elements of the list from left.
#2 Example :-
The number of elements inserted need not equal to number of elements replaced. Python can grows or shrinks the list as per requirements.
list2 = [ 10, 20, 30]
list2[ 1:3 ] = [ 5, 15, 25, 35 ]
print( list2 )
Output
[ 10, 5, 15, 25, 35 ]
Note:- Here we can see the number of elements we want to insert is 4 and the number of elements replaced is 2.
#3 Example
We can also replace a single element with more than one element.
list3 = [ ‘a’, ‘b’, ‘c’, ‘d’ ]
list3[ 2 ] = [ 10, 20, 30 ]
print( list3 )
Output
[ ‘a’, ‘b’, 10, 20, 30, ‘d’ ]
#4 Example :-
We can also insert element without replacing any element.
list4 = [ 10, 20, 30 ]
list4[ 2:2 ] = [ 1, 2, 3 ]
print( list4 )
Output
[ 10, 20, 1, 2, 3, 30 ]
You have learned how to modify multiple element in python list
Important Links: Informatics Practices
What is Python List
Characteristics of Python List
How to Create Python List
How to Traverse a list in Python
How to Manipulate list in Python
Slicing in Python List
Built in function of Python List