Replacing two elements of a list in place with a function [python 3] -


i want create function such when enter list , parameters, replace 2 items of list each other. code needs in place.

the code needs start so:

def reverse_sublist(lst,start,end):  ... 

an example of it's supposed do:

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

i tried write pseudo code of how it:

start=i, end=n #1# make copy of both lst[i], lst[n] inside list, right next original #2# lst[i]=lst[n+1] , lst[n]=lst[i+1]  delete lst[i+1], lst[n+1] 

i began learning python have several questions:

how can define parameters of function (#1#) ?

how can these operations (#2#) on list function ?

thanks in advance.

i think want is:

def reverse_sublist(lst, start, end):     lst[start:end] = reversed(lst[start:end]) 

note definition of 3 arguments function on first line, in parentheses after name of function.

your current pseudocode appears swapping items @ start , end, not example shows. if did want this, do:

def swap_items(lst, index1, index2):     lst[index1], lst[index2] = lst[index2], lst[index1] 

an additional note on first approach: if add items list throw off indexing rest of list. example, try test implementation of pseudocode:

def test(lst, start, end):     lst.insert(start+1, lst[start])     lst.insert(end+1, lst[end])     print(lst)     lst[start] = lst[end+1]     lst[end] = lst[start+1]     print(lst)     del lst[start+1]     del lst[end+1]     print(lst) 

the result gives not [5, 2, 3, 4, 1] expecting:

>>> test([1, 2, 3, 4, 5], 0, 4) [1, 1, 2, 3, 4, 4, 5] # after insert [4, 1, 2, 3, 1, 4, 5] # after swap [4, 2, 3, 1, 4] # after del 

instead, have insert , swap on end+2 , end+1 account item insert @ start+1:

def test(lst, start, end):     lst.insert(start+1, lst[start])     lst.insert(end+2, lst[end+1])     lst[start], lst[end+1] = lst[end+2], lst[start+1]     del lst[start+1]     del lst[end+1] 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

How to get multiresult with multicondition in Sql Server -