Home > Blockchain >  Mistake in list comprehension
Mistake in list comprehension

Time:11-26

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?

CodePudding user response:

I do not think list comprehension is required for intersection of 2 lists. Anyways you can modify your code to-

list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one for b in list_two if a == b and a not in new_list]
print(new_list)

you can also do-

list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = [a for a in list_one if a in list_two and a not in new_list]
print(new_list)

You can convert it into set and use set1.intersection(set2).

list_one = [1,3,4,5]
list_two = [1,5]
new_list = []
new_list = list(set(list_one).intersection(set(list_two)))
print(new_list)

CodePudding user response:

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

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

CodePudding user response:

This is a simple approach with sets,

list_1 = [1,2,3,4,5]
list_2 = [5,4,7,7,5,1,2,8,9]

new_list = list(set(list_1) & set(list_2))

print(new_list)

It uses the set intersection has a number of benefits compared to a list comprehension:

  • The input lists do not need to be sorted (though you can sort them by using sorted() function.
  • The input lists can have different lengths.
  • Presence of duplicates is taken care of automatically (sets don't admit those).
  • Related