You can use slices to very easily reverse a str
, list
, or tuple
(or basically any collection object that implements slicing with the step parameter). Here is an example of reversing a string, although this applies equally to the other types listed above:
s = 'reverse me!'
s[::-1] # '!em esrever'
Let's quickly look at the syntax. [::-1]
means that the slice should be from the beginning until the end of the string (because start
and end
are omitted) and a step of -1
means that it should move through the string in reverse.