I am working on the similarities helpers.py.

On checking check50, I found that the generator below does not work as intended, where input is ('This is one. This is two. This is three. This is two. This is one.' and 'This is three. This is two. This is four. This is five.'... ), which the generator does not exclude the line (Expected 2 matches, not 3), even though I have specified 'line not in returnlist'.

returnlist = [line for line in alist if (line in blist and line not in returnlist)]

after then I change it back to a standard for loop and it works perfectly.

for line in alist:
        if (line in blist) and (line not in returnlist):

so my question is, what makes the difference? I suspect that the generator creates all the answers before pushing to the returnlist, such that "line not in returnList" is simply checking an empty list from start to end. Thanks!


In the first version, the list comprehension is evaluated with the current value of returnlist, which you likely set to an empty list. It does not change over time.

Only after the new list has been generated, it is assigned to variable returnlist, replacing whichever value the variable had (so likely replacing your empty list).

Which means you can't check for duplicates that way.

  • thankyou @Blauelf! Then is there a more Pythonic way to write the above for-loop? perhaps using recursion will be considered more 'pythonic'? – morgan Feb 11 '19 at 13:35
  • I used sets, not sure whether that's more "Pythonic". Sets automatically de-duplicate content, plus they have an intersection operator, so I don't have to write my own loop for that. – Blauelf Feb 11 '19 at 14:38
  • I see. Thanks!! – morgan Feb 12 '19 at 4:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .