I often see [::-1] used in Python programming challenge submissions used for iterating over strings and lists in reversed order.
I have to confess that I never particularly liked this short but somewhat cryptic version of
But, as always, instead of arguing about something that is a matter of taste, we’ll pick the winner based on objective metrics.
First, let’s take a look at the bytecode and observe that first version uses more instructions -
vs
But what about benchmarks? Sure enough, there is a difference
vs
The difference is not huge in this case, but it’s more noticeable for strings
vs
for a small string
and is huge in case of lager strings
because unlike list slices that are fairly lightweight, string slices produce new strings and it’s certainly not cheap.
You can explore the difference further in colab notebook, but I now feel much less guilty of suggesting using reversed as part of code reviews.