I have a list, and I want to find the value 20 in the list and if it is present, replace the first instance with 3.
list1 = [5, 10, 15, 20, 25, 50, 20]
I have a list, and I want to find the value 20 in the list and if it is present, replace the first instance with 3.
list1 = [5, 10, 15, 20, 25, 50, 20]
Perform a linear search, or if the sequence can be disturbed, sort it and do a binary search. Then when 20 is found, note the index and replace it directly. eg
flag=0;
for(int i=0;i<list1.size();i++)
{
if(list1[i]==20 && flag==0)
{
list1[i]=3;
flag=1;
}
}
for python: finding and replacing elements in a list
I did it directly. This works for me:
while True:
if 20 in list1:
# getting index of the value
val_index = list1.index(20)
# replacing it by 3
list1[val_index] = 3
print(list1)
else:
break
and if you want only the first value should change then remove the while loop:
if 20 in list1:
# getting index of the value
val_index = list1.index(20)
# replacing it by 3
list1[val_index] = 3
print(list1)
I hope this works :)