Skip to content
Related Articles

Related Articles

Python – Swap K suffix with prefix

View Discussion
Improve Article
Save Article
  • Last Updated : 11 Oct, 2020
View Discussion
Improve Article
Save Article

Given a List, perform a swap of K prefix and suffix.

Examples:

Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 2
Output : [7, 9, 3, 1, 0, 1, 3, 5, 5, 6]
Explanation : Rear 2 and Front 2 elements swapped.

Input : test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9], K = 1
Output : [9, 6, 3, 1, 0, 1, 3, 5, 7, 5]
Explanation : Rear 1 and Front 1 element swapped.

Method #1: Using slice and range swap 

In this, we perform the task of getting the required slice using list slicing and perform range swap to swap elements. This is inplace method to solve this problem.

Python3




# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using range swap + slice()
  
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# performing range swap
test_list[:K], test_list[len(
    test_list) - K:] = test_list[len(test_list) - K:], test_list[:K]
  
# printing result
print("After prefix suffix swap : " + str(test_list))

Output

The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]

Method #2 : Using slice notation

In this we perform reconstruction of list elements using slicing each list performing slice.

Python3




# Python3 code to demonstrate working of
# Swap K suffix with prefix
# Using slice notation
  
# initializing list
test_list = [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# joining parts using slice
res = test_list[len(test_list) - K:] + \
    test_list[K: len(test_list) - K] + test_list[:K]
  
# printing result
print("After prefix suffix swap : " + str(res))

Output

The original list is : [5, 6, 3, 1, 0, 1, 3, 5, 7, 9]
After prefix suffix swap : [5, 7, 9, 1, 0, 1, 3, 5, 6, 3]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!