0

is there an easy way to detect if the entire contents of one list are in another?

if I have a list like this: li = [1,2]
and I have another which will have random values, I want the program to do something only if every value of li is in the second list.

I need a way to program this:

x = random.randint(0,10)
y = random.randint(0,10)
li = [1,2]
li2 = [x,y]


if every value of li2 is in li:
    do this
5
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by vegaseat
0

Hi!

I don't know if you would call this easy, but it seems to work:

def is_sublist( lst1, lst2 ):
     for elem in lst1:
         if elem not in lst2:
             return False
     return True

e.g.:

l1 = [1,2]
l2 = [2,4,6]
l3 = [1,2,3]
print is_sublist(l1, l2)   # --> False
print is_sublist(l1, l3)   # --> True

If you use sets instead of lists, there is a builtin function:

s1 = set([1,2])
s2 = set([2,3,4])
s3 = set([1,2,3])
print s1.issubset(s2)
print s2.issubset(s3)

Hope this helps.

Regards, mawe

0

You can use type()

x = random.randint(0,10)
y = random.randint(0,10)
li = [1,2]
li2 = [x,y]

test_list = []
if every_value of li2 is in li:
    if type(every_value) == type(test_list) :
       do this

Note that 'of li2 is in li' will compare entire list to list, not each element, assuming every_value is a list. It is not considered good code practice to use the letters 'el', 'eye', or 'oh' for variable names as they look too much like numbers and are confusing.

0

is there an easy way to detect if the entire contents of one list are in another?

if I have a list like this: li = [1,2]
and I have another which will have random values, I want the program to do something only if every value of li is in the second list.

I need a way to program this:

x = random.randint(0,10)
y = random.randint(0,10)
li = [1,2]
li2 = [x,y]


if every value of li2 is in li:
    do this

if your lists comparing only numbers, you can sort them first?

if sorted(li) == sorted(li2):
   do something
0

This will not work because list a and b are not the same length ...

a = [1, 2]
b = [2, 3, 6, 1]
# this will not work here ...
if sorted(a) == sorted(b):
    print 'a is in b'
else:
    print 'a is not in b'

Using set() will work, like mawe said ...

a = [1, 2]
b = [2, 3, 6, 1]
# this will work ...
if set(a).issubset(set(b)):
    print 'a is in b'
else:
    print 'a is not in b'

The next approach is pretty universal ...

def is_a_in_b(a, b):
    """returns True if all elements in list a are in list b, else False"""
    ax = []
    for x in a:
        for y in b:
            if x == y:
                ax.append(y)
    return a == ax

print is_a_in_b([1, 2], [2, 3, 6, 1])      # True
print is_a_in_b([1, 2], [1, 3, 7, 9, 4])  # False
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.