You can't use list.append
, as that appends to the end of the list. What you want is to append to the start of the list. For that use list.insert
. For more details see the list docs.
list_in_order = [1,2,3,4,5,6]
def reverse(L):
r = []
for i in L:
r.insert(0, i)
return r
print(reverse(list_in_order))
The other option is of course to use slice notation.
>>> [1,2,3,4,5,6][::-1]
[6, 5, 4, 3, 2, 1]
To make some constructive criticisms of the code in your question
- Don't refer to variables outside of the function, unless you really intend to use globals.
list_in_order.remove(i)
refers to your global variable, not your function argument (although they ultimately refer to the same thing in this case). It may have been a typo but its worth pointing out that it's not quite right.
- Don't use variable names that hide built in types.
list
, dict
, tuple
, set
etc... These are not good names for variables as they will hide those types from further use in the scope that variable exists in and it may be difficult to find the source of the errors you get as a result.
- Make your functions do one of two things; either modify the input (called in place modification) and return
None
or create a new collection and return that.
- Don't iterate over a collection while modifying it. See linked dupe for elaboration.