Python | Exchange of lists in a given range

Python Methods and Functions

Method # 1: Using a slice and swap list
Lists can be swapped just like a variable can be swapped in python, but the difference is that instead of a variable, we pass a truncated list for replacements.

# Python3 demo code
# replacing the sublist
# using list exchange and slicing

 
# initializing list

test_list = [ 1 , 4 , 5 , 8 , 3 , 10 , 6 , 7 , 11 , 14 , 15 , 2 ]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# using list swapping and slicing
# replacing sublist

test_list [ 1 : 3 ], test_list [ 6 : 8 ] = test_list [ 6 : 8 ], test_list [ 1 : 3 ]

 
# print result

print ( "The list after sublist swapping:" + str (test_list))

Exit:

 The original list is: [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2] The list after sublist swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2] 

Method # 2 : Using slice () + itertools.chain.from_iterable ()
The slice function can slice to retrieve a sublist from a list, and the from_iterable function helps to perform the swap function.

# Python3 code to demonstrate exchange
# sublist using slice () + itertools.chain. from_iterable ()

import itertools

 
# initializing list

test_list = [ 1 , 4 , 5 , 8 , 3 , 10 , 6 , 7 , 11 , 14 , 15 , 2 ]

 
# print original list

print ( "The original list is:" + str (test_list))

  # using slice () + itertools.chain.from_iterable ()
# replacing the sublist

slice_1 = test_list [ 1 : 3 ]

slice_2 = test_list [ 6 : 8 ]

slice_temp = [ slice ( 0 , 1 ), slice ( 6 , 8 ), slice ( 3 , 6 ) ,

slice ( 1 , 3 ), slice ( 8 , len (test_list))]

 

res = list (itertools.chain.from_iterable ([test_list [i]

for i in slice_temp]))

  
# print result

print ( "The list after sublist swapping:" + str (res))

Exit:

 The original list is: [1, 4, 5, 8, 3, 10, 6, 7, 11, 14, 15, 2] The list after sublist swapping: [1, 6, 7, 8, 3, 10, 4, 5, 11, 14, 15, 2] 




Get Solution for free from DataCamp guru