Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move function with Splice in Python

I'm trying to figure out how to do this following function from Javascript to Python:

function arraymove(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
}

Of course in Python we'de be working with Tuples and I'm not sure if there's a function like Splice in order to achive the same result.

like image 872
Louis Eloy Avatar asked Apr 14 '26 15:04

Louis Eloy


1 Answers

You can use insert method and move the desired element using just one line of code.

You would have to delete it and then just insert it at the new position. Using pop method you can remove one element from a specified position.

l.pop(fromIndex)

Then just use insert method and pass as argument the position where you want to insert the element.

l = [1,2,3,4,5]
def arraymove(arr, fromIndex, toIndex):
  l.insert(toIndex, l.pop(fromIndex))

print(l)
arraymove(l, 3, 1)
print(l)

Output

[1, 2, 3, 4, 5]
[1, 4, 2, 3, 5]
like image 66
Mihai Alexandru-Ionut Avatar answered Apr 16 '26 05:04

Mihai Alexandru-Ionut