Updated 13 days ago | GitHub
On this page

Reverse List

TIP101 Unit 1 Session 2 (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • What is the input?
    • A list of numbers, numbers.
  • What should the function return?
    • A new list with the same elements in reverse order. The original list is not changed.
  • What if the list is empty?
    • Return an empty list.
HAPPY CASE
Input: numbers = [1, 2, 3, 4]
Output: [4, 3, 2, 1]
Explanation: The last element comes first and the first element comes last.

EDGE CASE
Input: numbers = []
Output: []
Explanation: There is nothing to reverse, so the result is an empty list.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Create a reversed list by looping through each element in reverse and adding them to the end of another list.

1) Create a new list to hold the reversed values
2) Loop through each value in the original list, starting at the last index and decrementing by 1
  a) Add each value to the end of the new list
3) Return the new list

Alternative Ideas:

  • Loop through each value in the original list in the forwards direction, and use the insert() function to add elements to the beginning of the results list.
  • Use list slicing syntax.

⚠️ Common Mistakes

  • To visualize this strategy, it might help to try drawing out an example.
    • You’ve most likely reversed a “list” using this strategy in real life. For example, have you ever had to reverse the order of a stack of papers? How did you do it?

I-mplement

def reverse_list(numbers):
    reversed_list = []
    for i in range(len(numbers) - 1, -1, -1):
        reversed_list.append(numbers[i])
    return reversed_list

Alternative Solution:

def reverse_list(numbers):
    reversed_list = []
    for number in numbers:
        reversed_list.insert(0, number)
    return reversed_list

Alternative Solution:

def reverse_list(numbers):
    return numbers[::-1]