Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Problem No 8

Reverse a list in-place and by slicing

Easy

8 minute session

Summary

Return a reversed list either by creating a new reversed copy or by reversing the original list in-place.

Problem statement

Write a function reverse_list(lst, in_place=False). When in_place is False (the default), return a new list that is the reversed copy of lst using slicing. When in_place is True, reverse lst in-place and return the same list object (now reversed). The function should work for lists containing any types.

Task

Implement a function that can return a reversed copy of a list or reverse the list in-place based on a flag.

Examples

Slicing reversal (default)

Input

reverse_list([1, 2, 3])

Output

[3, 2, 1]

Explanation

Default behavior returns a new list reversed using slicing.

Input format

A list as the first argument and an optional boolean in_place flag.

Output format

A list that is the reversed version of the input list (either a new list or the original mutated list).

Constraints

Do not import external libraries. When in_place is True, mutate the provided list; when False, do not change the original list.

Samples

Sample input 0

reverse_list([1, 2, 3], True)

Sample output 0

[3, 2, 1]

Explanation 0

The original list is reversed in-place and returned.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

09:12 PM

Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.