133k views
2 votes
How to interchange first half of the array with second half of array in python?

User Loyola
by
5.7k points

1 Answer

7 votes

Answer:

Following are the code to this question:

l= []#defining an empty list

n=int(input("Enter total element you want to insert: "))#defining variable to input total element

for i in range(0,n):# defining loop to input value in list

insert=int(input())#defining variable insert to input value

l.append(insert) # adding the elemenents into the list

x=n//2#calculating midpoint

l1 =l[:x]#using slicing to hold first-half value in l1 list

l2 =l[x:]#using slicing to hold second-half value in l2 list

print("Before interchange: ")#print message

print ("list : ",l)#print input list

l3=l2 + l1#add value in l3

print("After interchange: ")#print message

#print(l3) #print list l3

print (str(l3)[1:-1])#print list l3

Output:

please find the attachment.

Step-by-step explanation:

Description of the code:

  • In the above python program, an empty list l is declared, in the next line, variable n is defined, that input the total number of the list elements. In the next line, the for loop is declared, which uses the insert variable input value and used the append method to add value in the list.
  • In the next step, the variable x is declared, which finds the midpoint of the list, and defines the l1 and l2 lists, that use slicing to hold the first and second half values.
  • In the last step, the l3 list is declared, that adds the l1 and l2 lists and use the print method to print its values.
How to interchange first half of the array with second half of array in python?-example-1
User Julien Sorin
by
5.1k points