Search code examples
python-3.xlist-comprehension

Mistake in list comprehension


Problem Solved!

I have two python lists of integers that are randomly generated. I want to find the numbers that are common between the lists.

Using list comprehension, I've come up with this:

new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]

However, this returns an empty list. I have a working program using loops that works perfectly:

for a in list_one:
    for b in list_two:
        if a == b and a not in new_list:
            new_list.append(a)

What mistakes have I made converting it to a list comprehension?


Solution

  • You can't reference the same list inside of a list comprehension.

    Thanks @Keith from the comments of the OP for pointing it out.