-1
# 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. 

4 Answers4

1

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
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
1

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]

Edit: Use backward indexing,

def rev(lst):
    for i,x in enumerate(list(lst)):
        lst[~i] = x
    return lst

You can do it also by list comprehension:

def reverse(lst):
    return [tmp[i] for i in range(0,len(lst)-1,-1)]
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
1

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]
cards
  • 3,936
  • 1
  • 7
  • 25
0

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
tebkanlo
  • 148
  • 1
  • 8