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

PythonServer Side ProgrammingProgramming

When it is required to split the list, and then add this first part to the end of the list, a simple iteration through the list and list slicing is required.

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

Below is a demonstration for the same −

Example

 Live Demo

def split_list(my_list, n_val, k_val):
   for i in range(0, k_val):
      first_val = my_list[0]
      for k in range(0, n_val-1):
         my_list[k] = my_list[k + 1]
      my_list[n_val-1] = first_val
my_list = [34, 42, 56, 78, 9, 0, 23]
list_len = len(my_list)
pos = 3
print("The list is :")
print(my_list)
print("The split_list method is being called")
split_list(my_list, list_len, pos)
for i in range(0, list_len):
print(my_list[i])

Output

The list is :
[34, 42, 56, 78, 9, 0, 23]
The split_list method is being called
78
9
0
23
34
42
56

Explanation

  • A method named ‘split_list’ is defined, that takes a list, and two values as parameters.
  • Using simple indexing, the array is split, and the first part of the list is put to the end of the list.
  • A list is created, and is displayed on the screen.
  • This method is called by passing the list as parameter.
  • The output is displayed on the console.
raja
Updated on 12-Mar-2021 11:57:55

Advertisements