-1

My goal is to remove any non-countries from the list, "Checklist". Obviously "Munster" is not a country. Portugal is though. Why does it get removed then?

checklist = ["Portugal", "Germany", "Munster", "Spain"]
def CheckCountry(i):
    with open("C:/Users/Soham/Desktop/Python Exercises/original.txt","r") as f:
        for countries in f.readlines():
            if countries==i:
                continue
            else:
                return True
        return False
for i in checklist:
    if CheckCountry(i)==True:
        index=checklist.index(i)
        checklist.pop(index)
    else:
        CheckCountry(i)
print(checklist)

Please tell me what is wrong with my code. Keep in mind I have not learned regex or lambda yet.

  • 1
    Does this answer your question? [strange result when removing item from a list](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – wjandrea Aug 22 '20 at 01:41

1 Answers1

0

I think your using the continue function improperly in this scenario. Your not allowing your function to get to the return False because of continue. So try this:

checklist = ["Portugal", "Germany", "Munster", "Spain"]
def CheckCountry(i):
   with open("C:/Users/Soham/Desktop/Python     Exercises/original.txt","r") as f:
      for country in f.readlines():
         if country != i:
            return False
   return True
for i in checklist:
   if CheckCountry(i) == False:
      checklist.pop(checklist.index(i))

print(checklist)

Also remember python doesn't require that you include an else statement after an if. So in your situation they are just taking up space. I don't know how your .txt file is set up but I'm assuming each line has only a single country. Since if they are multiple countries per line I suggest using a separate of some sort so that you can turn each line into a list like so:

def CheckCountry(i):
   with open("C:/Users/Soham/Desktop/Python     Exercises/original.txt","r") as f:
      for countries in f.readlines():
         country_lst = countries.split(',') # using , as a separator
         for x in country_lst:
            if x != i:
               return False
Maxim
  • 276
  • 2
  • 6