0

I have two lists

ListA = [1,9,6,3,2,4]

ListB = range(min(ListA),(max(ListA)+1))
i.e ListB = [1,2,3,4,5,6,7,8,9]

I want to check if all elements of ListA exists in ListB

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58

3 Answers3

4

Use issubset to achieve that (I prefer to rename your variables to make them more pythonic):

l1 = [1, 9, 6, 3, 2, 4]
l2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

>>> set(l1).issubset(set(l2))
True

You may also use issuperset as follows:

>>> set(l2).issuperset(set(l1))
True
ettanany
  • 19,038
  • 9
  • 47
  • 63
3

You may use set() to check ListA is subset of ListB as:

>>> ListA = [1, 9, 6, 3, 2, 4]
>>> ListB = [1,2,3,4,5,6,7,8,9]

>>> set(ListA) <= set(ListB)  # OR, using `set(ListA).issubset(set(ListB))`
True

OR, you may use all() to check that iteratively:

# Iterates over ListA and checks each item is in ListB
>>> all(item in ListB for item in ListA)
True
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • You can see ListA dont have elements 5,7,8. Then how can all elements of B are in A? – Shivkumar kondi Nov 21 '16 at 09:22
  • As my comment says it *"Iterates over ListA and checks each item is in ListB"*. What you just mentioned is opposite of what my code does. – Moinuddin Quadri Nov 21 '16 at 09:23
  • Yes moinuddin, I want to check if all element of A exist in B,print "Yes" else "No", but with above solution list A dont have elements 5,7,8 of list B. So it should be "No"/ False – Shivkumar kondi Nov 21 '16 at 09:30
  • In that case what you want is not what you asked for. Because, *all element of a*, are `[1, 9, 6, 3, 2, 4]` and all these elements are present in *b*. – Moinuddin Quadri Nov 21 '16 at 09:37
  • @CodeMonkey: Are you sure? Have you tried it? Check this refrence: https://docs.python.org/2.4/lib/types-set.html specially the table – Moinuddin Quadri Nov 21 '16 at 09:42
  • Sorry, I checked with the same size list with the same contents and it failed. I made the wrong assumption. Still it should be <=, otherwise it fails if all of the elements are the same. – CodeMonkey Nov 21 '16 at 09:43
  • `=` means whether you want the complete set to be part of sub-set, or just want to check of subset. Indeed I want the complete set match, updated the answer – Moinuddin Quadri Nov 21 '16 at 09:45
3

You could do this with subsets.

set(ListA).issubset(set(ListB))

Kevin Kendzia
  • 248
  • 1
  • 12