0

I was trying to write a program that would reverse a list in python3. I first tried:

def reverse(lst):
    """ Reverses lst in place.
    >>> x = [3, 2, 4, 5, 1]
    >>> reverse(x)
    >>> x
    [1, 5, 4, 2, 3]
    """
    n = len(lst)
    for i in range(n//2):
        lst[i], lst[n-i-1] = lst[n-i-1], lst[i]

It failed and the x I got was the original value. However, when I changed my code to this, it worked:

def reverse(lst):
    """ Reverses lst in place.
    >>> x = [3, 2, 4, 5, 1]
    >>> reverse(x)
    >>> x
    [1, 5, 4, 2, 3]
    """
    n = len(lst)
    for i in range(n//2):
        temp = lst[i]
        lst[i] = lst[n-i-1]
        lst[n-i-1] = temp
1
  • 1
    Your original code works just fine. Commented Oct 9, 2013 at 8:49

1 Answer 1

2

It works as expected:

>>> def reverse(lst):
...     n = len(lst)
...     for i in range(n//2):
...         lst[i], lst[n-i-1] = lst[n-i-1], lst[i]
...
>>> lst = [1,2,3,4,5]
>>> reverse(lst)
>>> print(lst)
[5, 4, 3, 2, 1]

BTW, why don't you use list.reverse?

>>> lst = [1,2,3]
>>> lst.reverse()
>>> lst
[3, 2, 1]
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah...worked for me now..I don't know what happened there.. This was just a problem I tried to solve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.