0

What I want to do is take names from namelist, compare those to names in banklist, and if there is an item in banklist which looks a lot like an item in namelist, I want to append that item to a closematchlist. The goal of this is to find items that occur in both lists, even if there is a spelling error in namelist. When I print(closematch), it works like intended: the close matches in banklist get found and printed. However, when I try to append those items to a list, the result of print(closematchlist) is [].

for name in namelist:
    closematch = difflib.get_close_matches(name, banklist, 1, 0.8)
    closematchlist = list()
    closematchlist.append(closematch)
    print(closematch)
print(closematchlist)```
  • 1
    Does this answer your question? [Common elements comparison between 2 lists](https://stackoverflow.com/questions/2864842/common-elements-comparison-between-2-lists) – Diggy. Jun 16 '20 at 12:41
  • 3
    put "closematchlist = list()" out of the for-loop – Andy Jun 16 '20 at 12:43
  • 1
    The problem is that you keep recreating closematchlist inside the loop - meaning you're emptying it on every iteration. remove the line closematchlist = list() – Roy2012 Jun 16 '20 at 12:44
  • 1
    This is a good use-case for a list comprehension (assuming the calls to `print` are just for debugging purposes and can be removed). `closematchlist = [difflib.get_close_matches(name, ...) for name in namelist]`. – chepner Jun 16 '20 at 12:44
  • Ahh wow Andy and Roy2012 that makes a lot of sense. I'm dumb! Thanks a lot for the answer! – user2296226 Jun 16 '20 at 12:47

1 Answers1

3

difflib.get_close_matches() is a list of close matches. You don't need to copy it to a new list.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • 2
    The OP might want a list of those lists, or maybe use `closematchlist.extend` instead; it's not clear from the question. – chepner Jun 16 '20 at 12:46
  • 1
    That's also a great point. It was still a learning moment though! Shouldn't have put closematchlist = [] inside the for loop. Thanks for your answer! – user2296226 Jun 16 '20 at 12:48