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

Swap First and Last Word

Swap the first and last words in Python while retaining middle-word order. Students split text, require two tokens, and rebuild the result with single spaces.

IntermediatePhase 5 - Category 3: Word OperationsExample 7 of 10
swap-first-and-last-word.py
1# Take string input
2s = input("Enter a string: ")
3
4# Swap first and last word
5words = s.split()
6if len(words) >= 2:
7 words[0], words[-1] = words[-1], words[0]
8 result = " ".join(words)
9 print(f"After swap: {result}")
10else:
11 print("Need at least 2 words")

Output

Enter a string: Hello World Programming
After swap: Programming World Hello

In this one

  • Swap token endpoints
  • Require two words
  • Preserve middle order

How it works

  1. 1

    Split text and require at least two tokens.

  2. 2

    Exchange words[0] and words[-1] together.

  3. 3

    Join and print the result.

Edge cases

What if only one word is entered?

What if only one word is entered?

Need at least 2 words is printed.

Are middle words reversed?

Are middle words reversed?

No. Only the two endpoints swap.

What's going on

The code requires at least two words before assigning the endpoints together. Both original endpoint values are read before either is replaced.

With red blue green, the result is green blue red; longer inputs retain their middle tokens unchanged. join normalizes separators to single spaces. Zero or one token reaches the message branch rather than pretending a meaningful two-word swap occurred.

What if only one word is entered? Need at least 2 words is printed.

Are middle words reversed? No. Only the two endpoints swap.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use paired assignment?

Pick an answer to check it.

Question 2

What if only one word is entered?

Pick an answer to check it.

Questions people ask

What if only one word is entered?

Need at least 2 words is printed.

Are middle words reversed?

No. Only the two endpoints swap.

Why use paired assignment?

To preserve both old endpoint values before writing.