Few stylistic points about your current solution:
- use
print()
as a function for Python 3 compatibility
- on the other hand, because you are running it on Python 2.x, you may avoid creating an extra list with
range()
and use xrange()
function (differences)
- according to PEP8, you need to have spaces around the operators
- you can use
end -= 1
shortcut instead of end = end - 1
The code with all the proposed changes applied:
def reverse(alist):
end = len(alist) - 1
limit = int(end / 2) + 1
for i in xrange(limit):
alist[i], alist[end] = alist[end], alist[i]
end -= 1
return alist
print(reverse([1, 2, 3, 4, 5, 6]))
Note that you don't have to return the alist
from the function, since your reverse operates "in-place" - it modifies the input list. In other words, if you would remove return alist
and run:
l = [1,2,3,4,5,6]
reverse(l)
print(l)
You would see [6, 5, 4, 3, 2, 1]
printed.
One more way to do the reverse "manually" can be to use the negative indexing (not sure if it fits your constraints):
def reverse(alist):
return [alist[-i] for i in range(1, len(alist) + 1)]
Or, an expanded version without a list comprehension:
def reverse(alist):
newlist = []
for i in range(1, len(alist) + 1):
newlist.append(alist[-i])
return newlist
Note that this is not working in place, it would return a new list.
reversed()
built-in ? If not, you could dodef reverse(alist): return alist[::-1]
– Dex' ter 12 hours ago