window

Python Morsels Exercise

Get each iterable item and the next N-1 items

2 bonuses 7 hints 12 solutions 221 users solved 12 reviews

I'd like you to write a function that returns "windows" of items from a given list. Your function should take a list and a number n and return a new list of tuples, each containing "windows" of n consecutive items. That is, each tuple should contain the current item and the n-1 items after it.

Here are some examples:

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> window(numbers, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> window(numbers, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> window(numbers, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]

Your window function should return an empty list if the given n is 0. It should also be able to accept strings, tuples, and other sequences.

This problem is challenging. I recommend solving the base problem before either of the bonuses.

Bonus 1


This is just a preview of the problem statement.

This exercise includes 2 bonuses and 7 hint links.

To solve this exercise, sign in to your Python Morsels account.

A learning habit for experienced Pythonistas

Profile picture of Trey

My name is Trey Hunner and I hold Python trainings for teams. I've spent countless hours refining my most interesting Python exercises into Python Morsels, a Python skill-building platform for folks who already know Python. Python Morsels is design to help you deepen your Python skills every week.

Sign up for Python Morsels to access this exercise and many more.

Join Python Morsels ✨