How do I reverse a sublist in a list in place?

Tam211 picture Tam211 · Mar 7, 2014 · Viewed 14.1k times · Source

I'm supposed to create a function, which input is a list and two numbers, the function reverses the sublist which its place is indicated by the two numbers. for example this is what it's supposed to do:

>>> lst = [1, 2, 3, 4, 5] 
>>> reverse_sublist (lst,0,4) 
>>> lst  [4, 3, 2, 1, 5]

I created a function and it works, but I'm not sure is it's in place. This is my code:

def reverse_sublist(lst,start,end):
    sublist=lst[start:end]
    sublist.reverse()
    lst[start:end]=sublist
    print(lst)

Answer

flakes picture flakes · Mar 7, 2014
def reverse_sublist(lst,start,end):
    lst[start:end] = lst[start:end][::-1]
    return lst