with_previous

Python Morsels Exercise

Looping helper to get each iterable item along with the previous item

3 bonuses 7 hints 10 solutions 212 users solved 18 reviews

I want you to write a function that accepts a sequence (a list for example) and returns a new iterable (anything you can loop over) that includes a tuple of each item and the previous item (the item just before it). The first "previous item" should be None.

For example:

>>> list(with_previous("hello"))
[('h', None), ('e', 'h'), ('l', 'e'), ('l', 'l'), ('o', 'l')]
>>> list(with_previous([1, 2, 3]))
[(1, None), (2, 1), (3, 2)]

There are three optional bonuses for this exercise.

Bonus 1


This is just a preview of the problem statement.

This exercise includes 3 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 ✨