Python: Reversing Words
What is the best way to do it? Depending on your viewpoint, either option could be, but what about for processing a ridiculously long string?

Python version used at time of writing: 3.11.x
Although it may not be the most useful thing to do it serves an example of micro optimisation. There are various ways to reverse words in a string and I have written two examples below, now lets assume we have a string variable named words which contains a sentence.
What is the best way to do it? Depending on your viewpoint, either option could be, but what about for processing a ridiculously long string?
List Comprehension
reversed_words = ' '.join(i[::-1] for i in words.split(' '))
To make it clearer, this is the same code in a typical for loop.
reversed_words = []
for i in words.split(' '):
reversed_words.append(i[::-1])
reversed_words = ' '.join(reversed_words)
Map
For those who haven't used map before it's is used to apply a function on all the elements of an iterable (e.g a list) and return map object, so in this instance it's given the reverse slicing operator [::-1]
as the function and the iterable is a list made from splitting the string at each occurance of a space.
reversed_words = " ".join(map(lambda word: word[::-1], words.split(' ')))
Performance
To test the performance both methods were tested using a single sentence as an input and also a whole book of Harry Potter. These were ran 1,000 times and results averaged to get a more reliable answer.
It is clear that in this instance map() is the more efficient method of reversing words, which is backwards to most use cases of map where lambda often leads to slower processing than standard list comprehension.
Type | Harry Potter | Sentence |
---|---|---|
List Comprehension | 679ms | 54μs |
Map | 135ms | 15μs |
Now the likelyhood of anyone needing to use this in an environment where this speed difference is important is low, but it does show that there are ways of optimizing that are not typically expected.
Comments ()