208k views
4 votes
Use the function design recipe to develop a function named reverse that takes a list, which may be empty. The function returns a new list that contains all the elements from the original list in reverse order. For example, when the function's argument is [4,2,3,2], the function returns the new list [2,3,2,4]. When the function's argument is an empty list, it returns a new empty list. Your function definition must have type annotations and a complete docstring. Your function must have exactly one loop. Your function is not permitted to call Python's built-in reversed function or the reverse method provided by type list. Use the Python shell to test reverse.

User Siracusa
by
7.2k points

1 Answer

6 votes

Final answer:

A Python function named 'reverse' is created without using built-in reverse methods. It uses a for loop to insert each element at the beginning of a new list, effectively reversing the order of elements. Type annotations and a docstring are included for clarity.

Step-by-step explanation:

Python Function to Reverse a List

To develop a function named reverse that takes a list and returns a new list with the elements in reverse order, we follow the function design recipe. This includes the definition of the function with type annotations, a complete docstring for documentation, implementation that ensures the function works properly, and testing the function in the Python shell to validate its correctness. This function will use a for loop to iterate over the original list and prepend each element to a new list, effectively reversing the order. Here is an implementation that satisfies the requirements:

def reverse(lst: list) -> list:
"""
Reverse a given list.

Parameters:
lst (list): A list to be reversed.

Returns:
list: A new list containing the elements from the original list in reverse order. An empty list returns an empty list.
"""
reversed_list = []
for item in lst:
reversed_list.insert(0, item)
return reversed_list

# Test cases
print(reverse([4,2,3,2])) # Output: [2,3,2,4]
print(reverse([])) # Output: []
User Stefan Reich
by
8.2k points

No related questions found