Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Generate sliding windows of size n

Create contiguous sliding windows from any sequence with a configurable step.

Python practice15 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Given a sequence (list, tuple, or string), produce all contiguous windows of length n. The windows should be taken by advancing the start index by 'step' each time. If n is greater than the sequence length, return an empty list. The function should work with any sliceable sequence and return windows of the same type elements (i.e., for strings return substrings, for lists return lists). Do not modify the original sequence.

Task

Implement a function that returns a list of contiguous windows (sublists or substrings) of size n from a sequence, supporting a step parameter.

Examples

Basic numeric list

Input

sliding_windows([1, 2, 3, 4], 2)

Output

[[1, 2], [2, 3], [3, 4]]

All contiguous windows of size 2 with default step 1.

Step greater than 1

Input

sliding_windows([1,2,3,4,5], 3, 2)

Output

[[1, 2, 3], [3, 4, 5]]

Windows start at indices 0 and 2 because step=2.

String input

Input

sliding_windows('abcdef', 3)

Output

['abc', 'bcd', 'cde', 'def']

Works on strings and returns substrings.

Input format

A sequence (list/tuple/string), integer n (window size), optional integer step (default 1).

Output format

A list of windows. Each window is of the same element type as the input (sublist for lists, substring for strings).

Constraints

n and step should be positive integers. If n > len(seq) return an empty list. The function must not mutate the input sequence.

Samples

Sample 1

Input

sliding_windows([1,2,3], 3)

Output

[[1, 2, 3]]

Window size equal to sequence length returns single window.