0

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]
TheTechRobo the Nerd
  • 1,249
  • 15
  • 28
  • 3
    Does this answer your question? [finding and replacing elements in a list](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list) – Steven May 19 '21 at 06:04
  • or this: https://stackoverflow.com/questions/1540049/replace-values-in-list-using-python ? – braulio May 29 '21 at 09:02

2 Answers2

0

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

0

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 :)

Sid
  • 13
  • 2
  • 4