A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-swapping-sublists-over-given-range/ below:

Swapping sublists over given range - Python

Swapping sublists over given range - Python

Last Updated : 11 Jul, 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)

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. 

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)

Output
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]

Explanation:

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)

Output
After swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2]

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4