How to modify multiple element in python list easiest way with 4 different methods

How to modify multiple element in python list

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

If you like my post please share it with your friends by simply clicking the below social media button, and Don’t forget to comment so we will update ourselves.

Share in a Single Click

Leave a Reply

Your email address will not be published. Required fields are marked *