Editor

Page Ranges

Advanced · Stretch · from Python Lists: Create, Access, Modify, and Loop Through Lists

From the lesson: Python Lists: Create, Access, Modify, and Loop Through Lists

Think about your favorite music playlist. It has a bunch of songs stored in a specific order. You can add new songs, remove old ones, rearrange them, or skip to song number five.

Read the lesson

A print dialog shows the pages you picked in a short form, joining runs of pages that follow each other. Write a function page_ranges(pages) that takes a list of page numbers and returns that text.

page_ranges([1, 2, 3, 5, 7, 8, 9])   # '1-3, 5, 7-9'
page_ranges([4, 10])                  # '4, 10'

The list can be in any order and can name a page more than once. A run of one page is written as the page alone. With no pages, return an empty string.

Return the answer instead of printing it: Check calls page_ranges() with its own lists, some of them hidden.

def page_ranges(pages):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
page_ranges([1, 2, 3, 5, 7, 8, 9])'1-3, 5, 7-9'
page_ranges([4, 10])'4, 10'

More List exercises

All Python exercises · 50 practice problems · Data Structures quiz