Python Program to Split the Array and Add First Part to the End (original) (raw)
Last Updated : 11 Nov, 2025
Given an array and an integer k, the task is to split the array from the kth position and move the first part to the end. For Example:
**Input: arr = [12, 10, 5, 6, 52, 36], k = 2
**Output: [5, 6, 52, 36, 12, 10]
**Explanation: Split the array at index k and move the first part [12, 10] (for k = 2) to the end.
Below are the different methods to perform this task:
Using deque.rotate() from collections
deque from the collections module allows efficient rotation of elements. Its rotate() method handles both left and right rotations internally without explicit shifting.
Python `
from collections import deque
arr = [12, 10, 5, 6, 52, 36] k = 2
d = deque(arr) d.rotate(-k) print(list(d))
`
Output
[5, 6, 52, 36, 12, 10]
**Explanation:
- **deque(arr): converts the list into a double-ended queue
- **rotate(-k): shifts the elements left by k positions
- **list(d): converts the deque back into a list
Using List Slicing
List slicing rotates a list by splitting it at position k taking elements from index k to the end first, then adding the first k elements to the end.
Python `
arr = [12, 10, 5, 6, 52, 36] k = 2
arr = arr[k:] + arr[:k] print(arr)
`
Output
[5, 6, 52, 36, 12, 10]
**Explanation:
- **arr[:k]: first k elements.
- **arr[k:]: remaining elements.
- Concatenating them gives the rotated array.
Using List Comprehension and Modulo
This method uses modular arithmetic to calculate rotated positions directly. It constructs a new list where each element is taken from (i + k) % len(arr).
Python `
arr = [12, 10, 5, 6, 52, 36] k = 2
n = len(arr) res = [arr[(i + k) % n] for i in range(n)] print(res)
`
Output
[5, 6, 52, 36, 12, 10]
**Explanation:
- ****(i + k) % len(arr):** wraps indices around the array, ensuring the rotation is circular.
- Creates a rotated version without modifying the original array.
Using extend()
Slicing combined with extend() achieves rotation while demonstrating list merging explicitly.
Python `
arr = [12, 10, 5, 6, 52, 36] k = 2
x = arr[:k] y = arr[k:] y.extend(x) print(y)
`