Rajat Bhardwaj
Rajat Bhardwaj

Reputation: 169

Easier way to check if an item from one list of tuples doesn't exist in another list of tuples in python

I have two lists of tuples, say,

list1 = [('item1',),('item2',),('item3',), ('item4',)] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple

Expected output: 'item4' # Item that doesn't exist in list2

As shown in above example I want to check which item in tuples in list 1 does not exist in first index of tuples in list 2. What is the easiest way to do this without running two for loops?

Upvotes: 0

Views: 1442

Answers (7)

Rajendra Kumbar
Rajendra Kumbar

Reputation: 7

for i in list1:
  a=i[0]
  for j in list2:
      b=j[0]
      if a==b:
          break
  else:
      print(a)

Upvotes: 0

anon01
anon01

Reputation: 11171

that is a difference operation for sets:

set1 = set(j[0] for j in list1)
set2 = set(j[0] for j in list2)
result = set1.difference(set2)

output:

{'item4'}

Upvotes: 0

sj95126
sj95126

Reputation: 6908

Assuming your tuple structure is exactly as shown above, this would work:

tuple(set(x[0] for x in list1) - set(x[0] for x in list2))

or per @don't talk just code, better as set comprehensions:

tuple({x[0] for x in list1} - {x[0] for x in list2})

result:

('item4',)

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71580

Try set.difference:

>>> set(next(zip(*list1))).difference(dict(list2))
{'item4'}
>>> 

Or even better:

>>> set(list1) ^ {x[:1] for x in list2}
{('item4',)}
>>> 

Upvotes: 0

mozway
mozway

Reputation: 260640

You don't really have a choice but to loop over the two lists. Once efficient way could be to first construct a set of the first elements of list2:

items = {e[0] for e in list2}
list3 = list(filter(lambda x:x[0] not in items, list1))

Output:

>>> list3
[('item4',)]

Upvotes: 0

qwerteee
qwerteee

Reputation: 307

This is the only way I can think of doing it, not sure if it helps though. I removed the commas in the items in list1 because I don't see why they are there and it affects the code.

list1 = [('item1'),('item2'),('item3'), ('item4')] # Contains just one item per tuple
list2 = [('item1', 'd',),('item2', 'a',),('item3', 'f',)] # Contains multiple items per tuple
not_in_tuple = []

OutputTuple = [(a) for a, b in list2]
for i in list1:
    if i in OutputTuple:
        pass
    else:
        not_in_tuple.append(i)

for i in not_in_tuple:
    print(i)

Upvotes: 0

no comment
no comment

Reputation: 10193

This gives you {'item4'}:

next(zip(*list1)) - dict(list2).keys()

The next(zip(*list1)) gives you the tuple ('item1', 'item2', 'item3', 'item4').

The dict(list2).keys() gives you dict_keys(['item1', 'item2', 'item3']), which happily offers you set operations like that set difference.

Try it online!

Upvotes: 0

Related Questions