How to use While Loop In Python
We can also use a while loop to replace values in the list. While loop does the same work as for loop. In the while loop first, we define a variable with value 0 and iterate over the list. If value matches to value that we want to replace then we replace it with the new value.
Python3
# Replace Values in a List using While Loop # define list l = [ 'Hardik' , 'Rohit' , 'Rahul' , 'Virat' , 'Pant' ] i = 0 while i < len (l): # replace hardik with shardul if l[i] = = 'Hardik' : l[i] = 'Shardul' # replace pant with ishan if l[i] = = 'Pant' : l[i] = 'Ishan' i + = 1 # print list print (l) |
Output:
['Shardul', 'Rohit', 'Rahul', 'Virat', 'Ishan']
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