Python Practice › List Programs › Program 28

Sublists with 5 or more elements

MediumList Programs · 28 of 100

Write a Python program to generate all consecutive sublists with 5 or more elements.

Advertisement
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

  1. Two loops pick start and end positions that are at least 5 apart.

Solution

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

More list programs

← All 100 List Programs

Leave a Comment