4

my question is pretty much as above:

if you have 2 lists as below, how can you check if all items in the first list are in the second list. eg

list_one=[1,2,3]
list_two=[1,2,3,4]

my current attempt is just "if all list_one in list_two:"

but this condition never seems to be filled and so nothing further takes place. Any help would be appreciated thanks :)

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
OmarAlKamil
  • 49
  • 1
  • 2

5 Answers5

8

The all() function is used to check if all the condition are satisfied .We are getting elements from list_1 and checking if that is available in list_2 if all are available then we print "yes"

list_one=[1,2,3] 
list_two=[1,2,3,4]
if all(a in list_two for a in list_one):
    print "yes"
The6thSense
  • 8,103
  • 8
  • 31
  • 65
  • 2
    You can explicitly exit a loop with `break` on finding the stop condition, or use a `while` loop whose predicate includes the stop condition. – TigerhawkT3 Jul 13 '15 at 18:25
4

You can use all with a generator expression, this will allow short-circuiting upon finding the first element that doesn't occur in your second list.

>>> list_one=[1,2,3]
>>> list_two=[1,2,3,4]
>>> all(i in list_two for i in list_one)
True
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
3

I simply create a difference of sets and check is length.

assert len(set([1,2,3]) - set([1,2,3,4])) == 0

Note that in boolean context empty sets (like any other containers) are falsy, so you can simply so something like:

if set(seq1) - set(seq2):
    do_something()
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0
>>> l1 = [1,2,3,4,5]
>>> l2 = [3,2,1,5,4]
>>> for i in l1:
...    if i not in l2:
...      print('doh')
ey3
  • 11
  • 2
0

You can check for individual items in the list_one.

count=0
for i in list_one:
    if i in list_two:
        count += 1

    if count==len(list_one):
        print("All items covered!")
Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74