# Function that takes array as parameter and returns a reverse array
# using loop
def reverse_list(arr = []):
for i in arr[::-1]:
print(i)
arr_num = [1, 2, 3, 4, 5]
print(reverse_list(arr_num))
I want my function to take an array as a parameter, but I'm not sure if the structure /code of it is correct.
CodePudding user response:
Simply create a new array inside the function and either append each values before returning it
def reverse_list(arr = []):
new_arr = []
for i in arr[::-1]:
# print(i)
new_arr.append(i)
return new_arr
arr_num = [1, 2, 3, 4, 5]
print(reverse_list(arr_num))
Or in short assign the reversed array to the new array
def reverse_list(arr = []):
new_arr = arr[::-1]
return new_arr
CodePudding user response:
Your function will not work since it's not returning the list.
Here is one way to solve this problem:
def reverse_list(arr):
result = []
for i, _ in enumerate(arr): # try to use enumerate - it's better
result.append(arr[~i]) # use the backward indexing here
return result
CodePudding user response:
you can simply use the reversed
builtin function;
>>> reversed([1,2,3,4])
[4,3,2,1]
but if you wanted to have a function to return it, i will advise to use the slice
indexing:
def rev_list(lst):
return lst[::-1]