![]() |
VOOZH | about |
We are given a list and our task is to swap two sublists within the given list over specified ranges.
For example, in the given a list [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2], swapping the elements in the range [1:3] with [6:8] will yield the list [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2].
In this method we swap sublists by slicing specific ranges within the list and the sliced sublists are exchanged directly just as variables are swapped in Python, to better understand this see the example below:
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]
Explanation: li[1:3] and li[6:8] represent the sublists to be swapped and these ranges are assigned to each other directly.
This method uses the slice() function to extract the sublists to be swapped and then the itertools.chain function is used to merge the list slices in the desired order thus resulting in a swapped list.
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]
Explanation:
In this method we use the numpy library to perform sublist swapping. By converting the list into a NumPy array we can apply advanced indexing with boolean masks to swap the sublists and then the result is converted back to a list.
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]
Explanation: