0

I'm trying to find a reliable way to check if a positional list element in a list2 (all same length) does not exist in any i for i in list1?

This looks like the opposite of what I need:

How to check if one of the following items is in a list?

>>> list1 = [('1', '2', '3'), ('a', 'b', 'c'), ('4', '5', '6')]
>>> list2 = [('a', 'b', 'c'), ('m', 'n', 'b'), ('p', 'q', '6')]
>>> print(any(z in [i[2] for i in list1] for z in [z for x,y,z in list2]))
True

Ideally I want ('m','n,'b') of list2 because 'b' is not found in any 3rd element of list1, so how do I segregate it out?

Instead of 'any' I am looking for this sort of pseudo code:

print x,y,z from list2 if 'z' is not found in any 3rd position element in all the lists present in "list1"
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
oj43085
  • 115
  • 2
  • 11

1 Answers1

1

Create a set of all third elements from the first list, then test your tuples from the second list against the set:

third_positions = {t[2] for t in list1}
[t for t in list2 if t[2] not in third_positions]

Storing the values to test again first is far more efficient, than to loop over all the values again each time.

Demo:

>>> list1 = [('1', '2', '3'), ('a', 'b', 'c'), ('4', '5', '6')]
>>> list2 = [('a', 'b', 'c'), ('m', 'n', 'b'), ('p', 'q', '6')]
>>> third_positions = {t[2] for t in list1}
>>> print([t for t in list2 if t[2] not in third_positions])
[('m', 'n', 'b')]

If you must use any(), then that is possible too, but that incurs a loop over list1 for every tuple in list2, so O(NM) instead of O(N):

[t for t in list2 if not any (t[2] == u[2] for u in list1)]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343