How to check if a list contains another list of different values

Question:

i would like to know how to check if a list encompases another list regardless of similar values contains.
given the example posted below, i want to have a condition checks for existence of a list inside a list. in other words, for the values of l1 the check should return False and for l2, the check should return True

please let me know how to achieve that

code

l1 = [1,2,3]
l2 = [4,5,[6]]
Asked By: LetsamrIt

||

Answers:

To check if one list contains another list of different values, you can use the in keyword in an if statement. For example:

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

if [6] in l1:
    print("l1 contains [6]")
else:
    print("l1 does not contain [6]")

if [6] in l2:
    print("l2 contains [6]")
else:
    print("l2 does not contain [6]")

This code will check if the list [6] is contained in the lists l1 and l2, and print a message indicating whether it is or not. The output will be:

l1 does not contain [6]
l2 contains [6]

This approach works because the in keyword checks if an element is contained in a list, regardless of the values of the elements. In this case, the element being searched for is the list [6], and the in keyword will return True if this list is contained in the list being searched, and False otherwise.

Another option is to use the any function, which returns True if any element in a list satisfies a given condition, and False otherwise. For example:

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

if any(isinstance(x, list) for x in l1):
    print("l1 contains a list")
else:
    print("l1 does not contain a list")

if any(isinstance(x, list) for x in l2):
    print("l2 contains a list")
else:
    print("l2 does not contain a list")

This code will check if any element in the lists `

Answered By: Unexpected

IIUC, you can use any in combination with isinstance:

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


def contains_list(lst):
    return any(isinstance(e, list) for e in lst)


print(contains_list(l1))
print(contains_list(l2))

Output

False
True

Using isinstance is the canonical way of checking type in Python.

Answered By: Dani Mesejo

This is what you’re looking for

def contains_lists(ls):
    return any([type(x) == list for x in ls])
Answered By: gimix
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.