Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 934
Tam211 Avatar asked Mar 07 '14 17:03

Tam211


People also ask

How do you reverse a sublist in Python?

Python provides a builtin function reversed() i.e. The reversed() function returned a reverse iterator of the given list and then we passed this reverse iterator to the list() function, which iterated over all the elements of the list in reverse order and inserted them to a new list i.e. a list with reversed contents.

How do I reverse a list in place?

Reverse your lists in place using . reverse() and other techniques. Use reversed() and slicing to create reversed copies of your lists. Use iteration, comprehensions, and recursion to create reversed lists.

How do you flip elements in a list?

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.


3 Answers

def reverse_sublist(lst,start,end):
    lst[start:end] = lst[start:end][::-1]
    return lst
like image 53
flakes Avatar answered Oct 11 '22 12:10

flakes


Partial reverse with no temporary list (replace range with xrange if you use Python 2):

def partial_reverse(list_, from_, to):
    for i in range(0, int((to - from_)/2)):
        (list_[from_+i], list_[to-i]) = (list_[to-i], list_[from_+i])

list_ = [1, 2, 3, 4, 5, 6, 7, 8]
partial_reverse(list_, 3, 7)
print(list_)
like image 31
Valentin Lorentz Avatar answered Oct 11 '22 12:10

Valentin Lorentz


Easiest way to reverse a list in a partial or complete manner.

listVar = ['a','b','c','d']
def listReverse(list,start,end):
    while(start<end):
        temp = list[start]
        list[start] = list[end] #Swaping
        list[end]=temp
        start+=1
        end-=1
    print(list)


listReverse(listVar,1,3)

Output : - ['a', 'd', 'c', 'b']

like image 30
SSG Avatar answered Oct 11 '22 14:10

SSG