I have two lists, A
& B
, and I would like to test whether A
is contained in B
. By "contained" I mean that the elements of A
appear in the exact same order within B
with no other elements between them. What I'm looking for is very similar to the behavior of A in B
if they were strings.
Some elements of A
will be repeated. We can assume A
will be shorter than B
.
There are many answers to similar questions on SO, but most answer a different question:
A
an element of B
? (Not my question: B
is a flat list, not a list of lists.)A
contained in B
? (Not my question: I'm concerned about order as well.)A
a sublist of B
? (Not my question: I don't want to know whether the elements of A
appear in the same order in B
, I want to know if they appear exactly as they are somewhere in B
.)If the operation were implemented as the keyword containedin
, it would behave like this.
>>> [2, 3, 4] containedin [1, 2, 3, 4, 5]
True
>>> [2, 3, 4] containedin [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
False
>>> [2, 3, 4] containedin [5, 4, 3, 2, 1]
False
>>> [2, 2, 2] containedin [1, 2, 3, 4, 5]
False
>>> [2, 2, 2] containedin [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
False
>>> [2, 2, 2] containedin [1, 1, 1, 2, 2, 2, 3, 3, 3]
True
Is there a concise way to perform this operation in Python? Am I missing some important terminology that would have led me to the answer more quickly?
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
Check if element exist in list using list.count(element) function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.
Use any
with list slicing:
def contained_in(lst, sub):
n = len(sub)
return any(sub == lst[i:i+n] for i in range(len(lst)-n+1))
Or, use join
to join both lists to strings and use in
operator:
def contained_in(lst, sub):
return ','.join(map(str, sub)) in ','.join(map(str, lst))
Usage:
>>> contained_in([1, 2, 3, 4, 5], [2, 3, 4])
True
>>> contained_in([1, 2, 2, 4, 5], [2, 3, 4])
False
many people have posted their answers. but I want to post my efforts anyway ;) this is my code:
def containedin(a,b):
for j in range(len(b)-len(a)+1):
if a==b[j:j+len(a)]:
return True
return False
print(containedin([2, 3, 4],[1, 2, 3, 4, 5]))
print(containedin([2, 3, 4],[1, 1, 2, 2, 3, 3, 4, 4, 5, 5]))
print(containedin([2, 3, 4],[5, 4, 3, 2, 1]))
print(containedin([2, 2, 2],[1, 2, 3, 4, 5]))
print(containedin([2, 2, 2],[1, 1, 1, 2, 2, 2, 3, 3, 3]))
this is the output: True False False False True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With