patternpythonModerate
Reversing an array in Python
Viewed 0 times
arrayreversingpython
Problem
Reversing an array in Python without using a built-in function:
def reverse(alist):
end = len(alist)-1
limit = int(end/2) + 1
for i in range(limit):
alist[i],alist[end] = alist[end],alist[i]
end = end - 1
return alist
print reverse([1,2,3,4,5,6])Solution
The first solution that comes to mind is to take advantage of the powerful list comprehension and abuse the
The above is nothing more than the usual reversed for loop that you may find in other languages (like C / C++) as:
Details about the
which is very descriptive.
I'd go with this instead of your solution because it looks cleaner and I don't see any reasons of why it'd be slower or harder to understand.
xrange function:def reverse(some_list):
return [some_list[n] for n in xrange(len(some_list) - 1, -1, -1)]The above is nothing more than the usual reversed for loop that you may find in other languages (like C / C++) as:
for (int i = array.length - 1; i >= 0; i--)
{
// Do something ...
}Details about the
range function can be found here but basically, all you have to know about it is its prototype:range(start, stop[, step])which is very descriptive.
I'd go with this instead of your solution because it looks cleaner and I don't see any reasons of why it'd be slower or harder to understand.
Code Snippets
def reverse(some_list):
return [some_list[n] for n in xrange(len(some_list) - 1, -1, -1)]for (int i = array.length - 1; i >= 0; i--)
{
// Do something ...
}Context
StackExchange Code Review Q#155619, answer score: 12
Revisions (0)
No revisions yet.