Python Practice › List Programs › Program 27
Does a list contain a sublist?
Write a Python program to check whether a list contains another list as a consecutive run.
Input
[1, 2, 3, 4, 5] contains [3, 4]? contains [3, 5]?
Output
True False
Approach
- Compare each slice of the right length with the sublist.
Solution
def contains(big, small): n = len(small) return any(big[i:i + n] == small for i in range(len(big) - n + 1)) print(contains([1, 2, 3, 4, 5], [3, 4]), contains([1, 2, 3, 4, 5], [3, 5]))Output
True False
Line by line
Line 3
Every starting position is tried; any() stops at the first match.
Learn the concept
New to this topic? Read the lesson, then come back.