S2Q1 · Reverse Each Word¶
⚡ Quick Reference
Function: reverse_each_word(words: list) -> list
Core idea: Apply [::-1] to every string in the list via a list comprehension.
Key rules: - Reverse each string independently - Return a new list -- don't modify the original - Empty list input returns an empty list
Problem Statement¶
Problem
Write a function reverse_each_word(words) that takes a list of strings and returns a new list where every string is reversed. All elements are guaranteed to be strings.
Examples:
reverse_each_word(["apple", "cat", "python"])
['elppa', 'tac', 'nohtyp']
reverse_each_word(["hi", "go"])
['ih', 'og']
Understanding the problem¶
Each word is reversed independently -- the order of words in the list stays the same, only the characters within each word are reversed:
| Input word | Reversed |
|---|---|
"apple" |
"elppa" |
"cat" |
"tac" |
"python" |
"nohtyp" |
[::-1] works on any sequence
The slice s[::-1] reverses any sequence -- strings, lists, or tuples. For strings it returns a new string (strings are immutable in Python), so there's no in-place modification to worry about.
Solution approaches¶
Key takeaways¶
Slice reversal: s[::-1]
A slice with step -1 traverses the sequence backwards, producing a reversed copy. It works on strings, lists, and tuples. For strings it returns a new string since strings are immutable.
List comprehension for element-wise transforms
[f(x) for x in iterable] applies a function to every element and collects the results into a new list. This is the idiomatic replacement for a for loop with .append().
map() as a functional alternative
map(lambda w: w[::-1], words) applies the reversal lazily to each element. Wrapping in list() materialises it. Both map and list comprehensions produce the same result -- use whichever reads more clearly.