Skip to content

Instantly share code, notes, and snippets.

@nmpowell
Last active May 25, 2017 08:41
Show Gist options
  • Save nmpowell/4d9abd73e2671227f20965201de7dd06 to your computer and use it in GitHub Desktop.
Save nmpowell/4d9abd73e2671227f20965201de7dd06 to your computer and use it in GitHub Desktop.
Python snippets to check list contents
# Python snippets to check list contents
# Given two lists, A and B ...
# Check all the items from A are present in B:
set(B).issuperset(set(A))
# Given a list of substrings A and another list of (longer) strings B which might contain those substrings ...
# e.g.
A = ['one', 'two', 'three']
B = ['someone', 'twooo', 'trees', 'everyone']
# ... list items from B which contain any of the strings in A:
existing = [n for n in B if any(s in n for s in A)]
# ['someone', 'twooo', 'everyone']
# ... check at least one of each item from A is present in B (where A are substrings of items in B):
all(any(s in n for n in B) for s in A)
# False
# ... show which items from A are present in B:
[s for s in A if any(s in n for n in B)]
# ['one', 'two']
# ... show which items from A are missing from B:
[s for s in A if not any(s in n for n in B)]
# ['three']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment