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)
lst[::-1]
is the idiomatic way to reverse a list in Python, The following show how and that it was in-place:I have two ways for in-place reversal, the simple way is to loop through the list half-way, swapping the elements with the respective mirror-elements. By mirror-element I mean (first, last), (2nd, 2nd-last), (3rd, 3rd-last), etc.
The other way is similar to the above but using recursion as opposed to a "loop":
...
Yes, it's in place.
lst
is never rebound, only its object mutated.Try some
crazy slicing
, see Explain Python's slice notation and http://docs.python.org/2.3/whatsnew/section-slices.html[out]:
Not sure if you have a similar problem as mine, but i needed to reverse a list in place.
The only piece I was missing was [:]