How to use List Slicing In Python
Python allows us to do slicing inside a list. Slicing enables us to access some parts of the list. We can replace values inside the list using slicing. First, we find the index of variable that we want to replace and store it in variable ‘i’. Then, we replace that item with a new value using list slicing. Suppose we want to replace ‘Rahul’ with ‘Shikhar’ than we first find the index of ‘Rahul’ and then do list slicing and remove ‘Rahul’ and add ‘Shikhar’ in that place.
Syntax: l=l[:index]+[‘new_value’]+l[index+1:]
Python3
# Replace Values in a List using Slicing # define list l = [ 'Hardik' , 'Rohit' , 'Rahul' , 'Virat' , 'Pant' ] # find the index of Rahul i = l.index( 'Rahul' ) # replace Rahul with Shikhar l = l[:i] + [ 'Shikhar' ] + l[i + 1 :] # print list print (l) |
Output:
['Hardik', 'Rohit', 'Shikhar', 'Virat', 'Pant']
How to Replace Values in a List in Python?
In this article, we are going to see how to replace the value in a List using Python. We can replace values in the list in serval ways. Below are the methods to replace values in the list.
- Using list indexing
- Using for loop
- Using while loop
- Using lambda function
- Using list slicing
Contact Us