how to remove and replace an element in a list using python

Issue

    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

Solution

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()
functionA() 

You may also achieve the same result in a more concise way using index:

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

  name1 = input("choose a country you don't like:")
  index = countries.index(name1)
  if(index == -1):
    print("try again")
    functionA()
  else:
    name2 = input("choose a country you want like:")
    countries[index] = name2 # We can just replace name1 with name2.
    print(countries)
functionA()

countries.index(name1) returns -1 iff name1 is not in the list, otherwise it returns the index where we can find it.

Answered By – Stubborn

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.