Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

IntermediatePhase 5 - Category 3: Word OperationsExample 3 of 10
reverse-order-of-words.py
1# Take string input
2s = input("Enter a string: ")
3
4# Reverse words
5words = s.split()
6reversed_words = words[::-1]
7result = " ".join(reversed_words)
8
9print(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. 1

    Split input into word tokens.

  2. 2

    Reverse the list with [::-1].

  3. 3

    Join tokens with one space and print result.

Walk through Reverse Order of Words

Text: red blue green

  1. 1.split produces [red, blue, green] as word tokens.
  2. 2.The reverse slice produces [green, blue, red].
  3. 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.