Write a function that reverses the order of words in a sentence — the letters within each word stay the same.
reverse_words(sentence)
reverse_words("hello world") // → "world hello"
reverse_words("the quick brown fox") // → "fox brown quick the"
reverse_words("single") // → "single"
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.
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.
def reverse_words(sentence):
words = sentence.split()
result = []
for i in range(len(words) - 1, -1, -1):
result.append(words[i])
return " ".join(result)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.