Python Program to Split the array and add the first part to the end

When it is required to split the array and add the first part to the end, we can use list slicing or implement a rotation algorithm. This operation is commonly known as left rotation of an array.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Method 1: Using List Slicing

The simplest approach is to use Python's list slicing to split and rearrange the array ?

def split_and_rotate(arr, k):
    """Split array at position k and move first part to end"""
    n = len(arr)
    k = k % n  # Handle k greater than array length
    return arr[k:] + arr[:k]

# Example usage
my_list = [34, 42, 56, 78, 9, 0, 23]
pos = 3

print("Original list:")
print(my_list)

result = split_and_rotate(my_list, pos)
print(f"After splitting at position {pos}:")
print(result)
Original list:
[34, 42, 56, 78, 9, 0, 23]
After splitting at position 3:
[78, 9, 0, 23, 34, 42, 56]

Method 2: In-place Rotation

For memory-efficient operations, we can rotate the array in-place ?

def split_list_inplace(my_list, n_val, k_val):
    """Rotate array left by k positions in-place"""
    k_val = k_val % n_val  # Handle k greater than array length
    
    for i in range(0, k_val):
        first_val = my_list[0]
        for j in range(0, n_val-1):
            my_list[j] = my_list[j + 1]
        my_list[n_val-1] = first_val

# Example usage
my_list = [34, 42, 56, 78, 9, 0, 23]
list_len = len(my_list)
pos = 3

print("The list is:")
print(my_list)

print("Applying in-place rotation...")
split_list_inplace(my_list, list_len, pos)

print("Result:")
for element in my_list:
    print(element)
The list is:
[34, 42, 56, 78, 9, 0, 23]
Applying in-place rotation...
Result:
78
9
0
23
34
42
56

Method 3: Using Collections.deque

The deque data structure provides efficient rotation operations ?

from collections import deque

def rotate_with_deque(arr, k):
    """Rotate array using deque for efficiency"""
    dq = deque(arr)
    dq.rotate(-k)  # Negative for left rotation
    return list(dq)

# Example usage
my_list = [34, 42, 56, 78, 9, 0, 23]
pos = 3

print("Original list:")
print(my_list)

result = rotate_with_deque(my_list, pos)
print(f"After rotation by {pos} positions:")
print(result)
Original list:
[34, 42, 56, 78, 9, 0, 23]
After rotation by 3 positions:
[78, 9, 0, 23, 34, 42, 56]

Comparison

Method Time Complexity Space Complexity Best For
List Slicing O(n) O(n) Simple, readable code
In-place Rotation O(k*n) O(1) Memory-constrained situations
Collections.deque O(k) O(n) Frequent rotations

Conclusion

Use list slicing for simple operations and readable code. For memory efficiency, use in-place rotation. When performing frequent rotations, collections.deque offers the best performance.

Updated on: 2026-03-25T17:33:02+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements