Reverse Order of Words
Reverse token order with Python split, list slicing, and join. Students follow the three-stage word pipeline and see how extra whitespace becomes single spaces.
1# Take string input2s = input("Enter a string: ")34# Reverse words5words = s.split()6reversed_words = words[::-1]7result = " ".join(reversed_words)89print(f"Reversed words: {result}")
Output
Enter a string: Hello World Programming Reversed words: Programming World Hello
In this one
- Choose words as the unit
- Reverse a token list
- Normalize separators
How it works
- 1
Split input into word tokens.
- 2
Reverse the list with [::-1].
- 3
Join tokens with one space and print result.
Walk through Reverse Order of Words
Text: red blue green
- 1.split produces [red, blue, green] as word tokens.
- 2.The reverse slice produces [green, blue, red].
- 3.A single-space join produces green blue red.
Edge cases
Are repeated spaces preserved?
Are repeated spaces preserved?
No. split discards them and join inserts single separators.
What happens for one word?
What happens for one word?
Its text stays the same.
What's going on
First split turns the response into a word list. The slice [::-1] reverses that list, then join rebuilds text with one space between tokens.
For red blue green, the intermediate list becomes green, blue, red and the result is green blue red. This lesson focuses on that split-list-join pipeline. Original spacing is normalized, while letters inside each word remain unchanged.
Are repeated spaces preserved? No. split discards them and join inserts single separators.
What happens for one word? Its text stays the same.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which object is reversed?
Pick an answer to check it.
Question 2
Are repeated spaces preserved?
Pick an answer to check it.
Questions people ask
Are repeated spaces preserved?
No. split discards them and join inserts single separators.
What happens for one word?
Its text stays the same.
Which object is reversed?
The word list.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum