Reverse Words

Reverse Words

Write a function that reverses the order of words in a sentence — the letters within each word stay the same.

reverse_words(sentence)

Examples

reverse_words("hello world")           // → "world hello"
reverse_words("the quick brown fox")   // → "fox brown quick the"
reverse_words("single")                // → "single"

Walkthrough

Thinking it through

Break this into two separate problems: splitting the sentence into words, and then visiting those words in reverse order.

def reverse_words(sentence):
    words = sentence.split()
    result = []
    for i in range(len(words) - 1, -1, -1):
        result.append(words[i])
    return " ".join(result)

sentence.split() with no arguments splits on whitespace and gives you a clean list of words — "the quick brown fox".split() becomes ["the", "quick", "brown", "fox"].

To walk that list from the last index back to the first, range(len(words) - 1, -1, -1) is the three-argument form from the loops lesson: start at len(words) - 1 (the last valid index), stop before -1 (i.e., stop after reaching index 0), stepping by -1 each time. For a 4-word list, that produces 3, 2, 1, 0 — exactly the indices in reverse order.

Appending words[i] for each of those indices builds result in reverse order, and " ".join(result) turns it back into a sentence.

A shorter alternative

Once you're comfortable with this loop-based version, it's worth knowing Python has a much shorter way to reverse a list: list(reversed(words)), or even simpler, slicing with words[::-1]. Both do exactly what the loop above does. This course starts with the explicit loop so the mechanics of reversing are clear — but in your own code, prefer the built-in.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.