-2

How should I fix this code in order to get a list that is in the reverse order of sequence s?

def reverse(s):
    """Return a list that is the reverse of sequence s.

    >>> reverse([1,2,3])
    [3, 2, 1]
    """
    rs = []
    for element in s:
        rs = s + rs
    return rs
Yooni
  • 9
  • 1
  • 1

2 Answers2

1

I'd actually do something like this (I'm assuming you cant use reversed()). This uses slicing notation to reverse a list.

def reverse(s): 
    return s[::-1]

I'm also assuming you need to wrap this in a function, you could just use the index notation on its own.

EDIT:

Here is a bit of an explanation of the [::-1] operation:

Slicing notation is of the format [start_point:end_point:step]

The start_point is not specified, this becomes the length of the list so the operation starts at the end.

The end_point is also not specified, this becomes -1 so the operation will end at the start.

The step is -1, so it will iterate backwards in steps of 1 (i.e. every element of the list).

This will create a shallow copy of your original list. This means the list you pass into reverse(s) will remain the same.

Example for clarification:

>>> x = [1, 2, 3]
>>> y = x[::-1]
>>> x
[1, 2, 3]
>>> y
[3, 2, 1]
RHSmith159
  • 1,823
  • 9
  • 16
0

parameter passed to function is of type list.

def reverse(s):
    return s[::-1]
Vaibhav Patil
  • 132
  • 1
  • 6