Python Practice › List Programs › Program 27

Does a list contain a sublist?

MediumList Programs · 27 of 100

Write a Python program to check whether a list contains another list as a consecutive run.

Advertisement
Input
[1, 2, 3, 4, 5] contains [3, 4]? contains [3, 5]?
Output
True False

Approach

  1. Compare each slice of the right length with the sublist.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment