Swapping sublists over given range - Python
Last Updated :
28 Jan, 2025
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:
Python
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)
OutputAfter 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.
Python
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)
OutputAfter 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.
Python
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)
OutputAfter 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.
Similar Reads
Python - Reverse Range in String List Given a string list, reverse each element of string list from ith to jth index. Input : test_list = ["Geeksforgeeks", "Best", "Geeks"], i, j = 1, 2 Output : ['ee', 'es', 'ee'] Explanation : Range of strings are extracted. Input : test_list = ["Geeksforgeeks"], i, j = 1, 7 Output : ['eeksfor'] Explan
3 min read
Python - Extract tuples with elements in Range Given list of tuples, extract tuples having elements in range. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6 Output : [(5, 6)] Explanation : Only 1 tuple lies in range of 5-6. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10 Output :
4 min read
Python | Alternate range slicing in list List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let's discuss how this particular problem can be solved. Method #1 : Using list comprehension List compr
6 min read
Python - Filter Rows with Range Elements Given a Matrix, filter all the rows which contain all elements in the given number range. Input : test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5 Output : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]] Explanation : 2, 3, 4, 5 all are present in above rows. Input :
5 min read
Python - Filter Range Length Tuples We are given a list of tuples where each tuple contains multiple elements, and our task is to filter out tuples whose lengths do not fall within a specified range. For example, if we have a = [(1, 2), (3, 4, 5), (6,), (7, 8, 9, 10)] and the range (2, 3), we should keep only tuples with 2 or 3 elemen
3 min read