Swapping sublists over given range - Python
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].
Using List Slicing
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:
li = [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2]
# Swapping sublists using slicing
li[1:3], li[6:8] = li[6:8], li[1:3]
print("After swapping:", li)
Output
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.
Using slice() and itertools.chain
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.
import itertools
li = [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2]
# Extracting slices and creating the swapped list
slices = [slice(0, 1), slice(6, 8), slice(3, 6), slice(1, 3), slice(8, len(li))]
res = list(itertools.chain.from_iterable([li[s] for s in slices]))
print("After swapping:", res)
Output
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]
Explanation:
- slice() function is used to define specific ranges of the list: [0:1], [6:8], and so on.
- itertools.chain.from_iterable() combines these slices into a new list in the swapped order.
Using numpy
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.
import numpy as np
li = [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2]
arr = np.array(li)
# Creating masks for sublists to swap
mask1 = np.zeros(len(arr), dtype=bool)
mask2 = np.zeros(len(arr), dtype=bool)
mask1[1:3], mask2[6:8] = True, True
# Swapping the sublists
arr[mask1], arr[mask2] = arr[mask2], arr[mask1]
# Converting the NumPy array back to a list
res = arr.tolist()
print("After swapping:", res)
Output
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]
Explanation:
- Boolean masks (mask1 and mask2) mark the positions of the sublists to be swapped.
- These masks are used for element-wise swapping within the NumPy array, ensuring direct manipulation of the targeted ranges.