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

In this article, we will learn to split the array and add the first part to the end of the array using the python program.


Example

k = 2
arr = [1, 2, 3, 4, 5, 6] ==========>   [3, 4, 5, 6, 1, 2]


Explanation

  • First we split the array
  • Second we add the array to end of the array
  • Lastly, we print the array


Program

Method 1 :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Split the array and add the first part to the end in python
# initialize the array
arr = [1, 2, 3, 4, 5, 6]

# length of an array
n = len(arr)

# position
k = 2

# Start rotating the array
# itrate the loop from 0 to k
for i in range(0, k):    
    # the first element of array stored in first variable 
    first = arr[0]
    
    for j in range(0, n-1):    
        # shift all the other element of array by one    
        arr[j] = arr[j+1]
            
    # then first element of array will be added to the end    
    arr[n-1] = first  

# print the array
print(arr)

Method 2:

1
2
3
4
5
6
# array
arr = [1, 2, 3, 4, 5, 6] 
k = 2

first = arr[:k]
print(arr[k::] + first[::])

Output
[3, 4, 5, 6, 1, 2]


Next Post Previous Post
No Comment
Add Comment
comment url