'how to remove and replace an element in a list using python
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 1:[1]
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.
Solution 2:[2]
1 If the code is all in functionA
2 should traverse the length of countries (so that the last element can be judged)
3 should use continue to jump out of this loop instead of callback
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()
Solution 3:[3]
In the future you should try and better explain the issues that you are facing, regardless of the complexity of your problem.
(It's worth mentioning that Python already has built in methods to find the index of an element in an array but I'm assuming you wanted to implement something yourself)
Now, the issue with your function is that if the first name does not match the input, the function is called again instead of moving to the next iteration. The simplest and quickest solution would be to add a flag that checks if the selected country was found. Also, if you need the index then a more pythonic way to loop over the list would be to use the enumerate function. So finally:
def functionA():
countries = ["Nigeria", "Uganda", "America", "Chad"]
print(countries)
was_found = False
name1 = input("choose a country you don't like:")
for i, country_name in enumerate(countries):
if country_name == 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)
was_found = True
break
if not was_found:
print("try again")
functionA()
A more elegant solution would be not to add the retry logic into this function in the first place and instead just return a default value initialized with None or an empty string, and handle that outside the function.
Solution 4:[4]
try this
def functionA():
countries = ["Nigeria", "Uganda", "America", "Chad"]
removeIndex = 0
print(countries)
while True:
name1 = input("choose a country you don't like:")
if name1 not in countries:
print("try again")
continue
print(f"The selected country is {name1}")
removeIndex = countries.index(name1)
countries.pop(removeIndex)
name2 = input("choose a country you want like:")
countries.insert(removeIndex, name2)
print(countries)
break
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | LaiZu |
| Solution 3 | |
| Solution 4 |
