0

I was struggling to properly title this question but I will try and explain this situation.

I have two lists

l1=['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19', 'rmmweekly']
l2=['beststreet', 'borocd', 'bestfrom', 'rmmweekly','weird','noises']

l1 will always remain the same.

l2 can either contain the exact items as l1 or have only some of the items as l1 and in any scenario there can be extra items in the list.

GOAL: find only the missing items in l2 that are in l1 (disregard the extra items in l2)

here is my full code for this, it works totally fine I just feel like I am overthinking this and what I want can have a simpler more pythonic workflow

l1=['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19', 'rmmweekly']
l2=['beststreet', 'borocd', 'bestfrom', 'rmmweekly','weird','noises']

result = [[n if n in l1 else None, n if n in l2 else None] for n in set(l1 + l2)]

missing_columns=[]
for r in result:
    if None in r:
        exists= [z for z in l1 if z in r]
        if exists:
            missing_columns.append(exists[0])
print missing_columns
ziggy
  • 1,488
  • 5
  • 23
  • 51
  • Are these lists or sets, i.e. are the elements unique or not? Or in any case, do you need to retrieve just a set of the missing elements or a sublist, i.e. a list which maintains order and number of occurences? – ovimunt Aug 20 '19 at 17:29

3 Answers3

4
print([item for item in l1 if item not in l2])
ipaleka
  • 3,745
  • 2
  • 13
  • 33
0

Use set difference

>>> set(l1).difference(l2)
{'noises', 'weird'}
Prem Anand
  • 2,469
  • 16
  • 16
0

To get only the difference you could use sets:

l1 = ['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19',
      'rmmweekly']
l2 = ['beststreet', 'borocd', 'bestfrom', 'rmmweekly', 'weird', 'noises']

s1 = set(l1)
s2 = set(l2)

# find missing items from s1 in s2
print(s1.difference(s2))
jgsedi
  • 227
  • 4
  • 18