I'd actually do something like this (I'm assuming you cant use reversed()
). This uses slicing notation to reverse a list.
def reverse(s):
return s[::-1]
I'm also assuming you need to wrap this in a function, you could just use the index notation on its own.
EDIT:
Here is a bit of an explanation of the [::-1]
operation:
Slicing notation is of the format [start_point:end_point:step]
The start_point
is not specified, this becomes the length of the list so the operation starts at the end.
The end_point
is also not specified, this becomes -1
so the operation will end at the start.
The step
is -1
, so it will iterate backwards in steps of 1 (i.e. every element of the list).
This will create a shallow copy of your original list. This means the list you pass into reverse(s)
will remain the same.
Example for clarification:
>>> x = [1, 2, 3]
>>> y = x[::-1]
>>> x
[1, 2, 3]
>>> y
[3, 2, 1]