1

I have two lists, I need to get matching items as sets.

list1 = [1,2,3]
list2 = [1,2,3,4]
a = [(x, y) for x in list1 if x in [y for y in list2]]

It gets X correctly but as expected it just gives the first item in nested list(y) instead of one that matched.

What is the easiest way to make this work and get X and Y that match in set? Any way to avoid using regex?

Update: To make it more clear, above is just example - the actual code is:

list1 = [(x, y) for x in new_ids if x.KWuser in [y.keyword for y in get_existing_KeyO]]

new_ids and get_existing_KeyO are lists of items from 2 different models:

get_existing_KeyO = list(KeyO.objects.filter(
keyword__in=[x['keyword'] for x in related_data]).all())
Nema Ga
  • 2,450
  • 4
  • 26
  • 49
  • You mean like common element between the two lists? – Iron Fist Dec 04 '15 at 07:11
  • 1
    `if x in [y for y in list2]` is the same as `if x in list2`, but slower. That's a side comment, your question doesn't make sense - why do you want the pair if they are both ... the same value? Why not `[(x, x) for x in list1 if x in list2]` ? If you want differing values then it sounds like you want a key/value matchup - and a dictionary, not two lists. – TessellatingHeckler Dec 04 '15 at 07:12
  • 1
    `set(list1).intersection(list2)`? – hjpotter92 Dec 04 '15 at 07:14
  • I updated the original question. – Nema Ga Dec 04 '15 at 07:32

1 Answers1

2

If you are looking to get common elements between the two lists, you can do it using sets :

>>> set(list1).intersection(list2)
set([1, 2, 3])

But keep in mind that this will return to you only common elements (no repeating elements), Example:

>>> list1 = [1,2,3,7]
>>> list2 = [1,2,3,4,7,8,7,7,7]
>>> set(list1).intersection(list2)
set([1, 2, 3, 7])

You can also do it with list comprehension if that's what you want, this way:

>>>list1 = [1,2,3]
>>>list2 = [1,2,3,4]
>>>a = [x for x in list1 if x in list2]
>>> a
[1, 2, 3]

Here the list comprehension will be exhausted by the length of list1, so if you had:

>>> list1 = [1,2,3,7]
>>> list2 = [1,2,3,4,7,8,7,7,7]
>>> a = [x for x in list1 if x in list2]
>>> a
[1, 2, 3, 7]

You will not get the last elements 7,7,7 as the search was exhausted (limited) by the length of list1, but if you reverse it this way:

>>> a = [x for x in list2 if x in list1]
>>> a
[1, 2, 3, 7, 7, 7, 7]

Here all elements(common and repeating) are caught.

Alex Essilfie
  • 12,339
  • 9
  • 70
  • 108
Iron Fist
  • 10,739
  • 2
  • 18
  • 34