Output the interleaved list if the either list is longer


Python programming

Ask the user to input two lists. list which interleaves the two lists by taking 1 from the first list and then 1 from the second list. Output the interleaved list. If the either list is longer than the other append the remaining elements from it at the end.

Sample output1:

Please enter list 1: 1 5 10 20

Please enter list 2: 3 9 11 22

The combined list is 1 3 5 9 10 11 20 22

Sample output2:

Please enter list 1: 1 22 2 1 7

Please enter list 2: 11 33

The combined list is 1 11 22 33 2 1 7

Sample output3:

Please enter list 1: 1 2 4 8

Please enter list 2: 13 3 5 9 10 11

The combined list is 1 13 2 3 4 5 8 9 10 11

inp = input("Please enter list 1: ")

inp2 = input("Please enter list 2: ")

ls1 = [int(x) for x in inp.split()]

ls2 = [int(x) for x in inp2.split()]

ans = []

for i in range(len(ls1)):

   ans.append(ls1[-1-i])

   ans.append(ls2[i])

print("The combined list is", end = " ")

for i in ans:

   print(i,end = ' ')

What should I change?

Solution Preview :

Prepared by a verified Expert
Basic Computer Science: Output the interleaved list if the either list is longer
Reference No:- TGS02757604

Now Priced at $10 (50% Discount)

Recommended (92%)

Rated (4.4/5)