Home > Back-end >  how to remove and replace an element in a list using python
how to remove and replace an element in a list using python

Time:05-07

    def functionA():
countries = ["Nigeria", "Uganda", "America", "Chad"]
print(countries)

name1 = input("choose a country you don't like:")
for i in range(3):
    
    if countries[i] == name1:
        print(f"The selected country is {name1}")
        countries.pop(i)
        name2 = input("choose a country you want like:")
        countries.insert(i, name2)

        print(countries)
        break
        
    else:
        print("try again")
        functionA()

functionA()

I keep on running the program but the looping is always incorrect

CodePudding user response:

This is because of the logic inside of the for loop: in case the first element is not equal to name1, functionA gets called again. You should instead check if name1 was found at the end of the for loop.

def functionA():
  countries = ["Nigeria", "Uganda", "America", "Chad"]
  print(countries)

  name1 = input("choose a country you don't like:")
  found = False
  for i in range(len(countries)):  # More robust, in case you need to change the list's size
      
      if countries[i] == name1:
          print(f"The selected country is {name1}")
          name2 = input("choose a country you want like:")
          countries[i] = name2 # We can just replace name1 with name2.

          print(countries)
          found = True
          break
          
  if not found:
    print("try again")
    functionA()

CodePudding user response:

def functionA():
    countries = ["Nigeria", "Uganda", "America", "Chad"]
    print(countries)

    name1 = input("choose a country you don't like:")
    for i in range(len(countries)):
        if countries[i] == name1:
            print(f"The selected country is {name1}")
            countries.pop(i)
            name2 = input("choose a country you want like:")
            countries.insert(i, name2)

            print(countries)
            break

        else:
            print("try again")
            continue


functionA()

  • Related