Your function will not work since it's not returning the list.
Here is one way to solve this problem - using the for-loop:
def reverse_list(arr):
result = []
for i, _ in enumerate(arr): # try to use enumerate - it's better in most cases
result.append(arr[~i]) # use the backward indexing here
return result
Answer from Daniel Hao on Stack OverflowYour function will not work since it's not returning the list.
Here is one way to solve this problem - using the for-loop:
def reverse_list(arr):
result = []
for i, _ in enumerate(arr): # try to use enumerate - it's better in most cases
result.append(arr[~i]) # use the backward indexing here
return result
With a list comprehension together with the reversed build-in function (it returns a generator):
def reverse_list(lst):
return [v for v in reversed(lst)]
# or return list(reversed(lst))
Another version but without for-loop to highlight the underlying processes:
Using build-in function slice to select a range of items in a sequence object
and select an element from the container with __getitem__ subscription.
def reverse_list(lst):
# slice object
s = slice(None, None, -1)
# selection
return lst.__getitem__(s) # <--> lst[s]
loops - Traverse a list in reverse order in Python - Stack Overflow
python - How do I reverse a list or loop over it backwards? - Stack Overflow
How can I loop through an array forward and then backwards and then forwards and... etc with the modulus operator?
Reversing a range using a FOR LOOP
Videos
Use the built-in reversed() function:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
To also access the original index, use enumerate() on your list before passing it to reversed():
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.
You can do:
for item in my_list[::-1]:
print item
(Or whatever you want to do in the for loop.)
The [::-1] slice reverses the list in the for loop (but won't actually modify your list "permanently").
To get a new reversed list, apply the reversed function and collect the items into a list:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
To iterate backwards through a list:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]
Extended slice syntax is explained here. See also, documentation.