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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With