Home > database >  Python index change in the list
Python index change in the list

Time:04-26

# write a function that accepts a list and the indexes of two elements in the list,
# and swaps that two elements of the list, and return the swapped list. 
# for example, if the arguments of the function are [23,65,19,90]m index1 = 1, and index2 = 3,
# then it will return [23,90,19,65].


# Swap function

def swapLst(newLst):
    size = len(newLst)
     
    # Swapping
    temp = newLst[0]
    newLst[0] = newLst[size - 1]
    newLst[size - 1] = temp
     
    return newLst
     
newLst = [23,65,19,90]
print(swapLst(newLst))

Hello, My question: How can I change my code to change the any index in the list. My program only changes first and last index, I needed help with that. Thank you!

CodePudding user response:

You can swap variables in python using a, b = b, a, so you can swap list elements with their indexes:

a = [1, 2, 3, 1, 2, 3, 5] 

def swap(l, i, j):
    l[i], l[j] = l[j], l[i]
    return l
print(swap(a, 0, 1))

Output:

[2, 1, 3, 1, 2, 3, 5]

CodePudding user response:

In order to do so, you need to accept the other integers as arguments as well.
And swapping is easier as a, b = b, a
Code:

def swapLst(newlst, in1, in2): 
    newlst[in1], newlst[in2] = newlst[in2], newlst[in1]
    return newlst
 
newLst = [23,65,19,90] 
print(swapLst(newLst, 1, 3))

Output:

[23, 90, 19, 65]
  • Related