Hackbright Code Challenges

Reverse List in Place: Solution

Reverse List in Place: Solution

Problem

Reverse List in Place

Whiteboard

Easier

Concepts

Loops, Lists

Download

rev-list-in-place-solution.zip


Work through half of the list. For each item in the list, swap it with the item in the corresponding position counting from the back (so for the first item, swap it with the last; for the second, swap it with the second from the last, and so on).

The problem is that you don’t want to overwrite the value stored in either of those positions, so you can either use a temporary variable to store one of the values (thus abiding by the “small, constant amount of extra storage space”) or use the sneaky tuple unpacking syntax, like:

x, y = y, x
def rev_list_in_place(lst):
    """Reverse list in place.

    You cannot do this with reversed(), .reverse(), or list slice
    assignment!
    """

    # START SOLUTION

    for i in range(len(lst) // 2):
        lst[i], lst[-i - 1] = lst[-i - 1], lst[i]