Python Practice › List Programs › Program 28
Sublists with 5 or more elements
Write a Python program to generate all consecutive sublists with 5 or more elements.
Input
[1, 2, 3, 4, 5, 6]
Output
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6]]
Approach
- Two loops pick start and end positions that are at least 5 apart.
Solution
items = [1, 2, 3, 4, 5, 6]subs = [items[i:j] for i in range(len(items)) for j in range(i + 5, len(items) + 1)]print(subs)Output
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6]]
Line by line
Line 2
j starts at i + 5, so every slice has at least 5 items.
Learn the concept
New to this topic? Read the lesson, then come back.