Skip to content
Related Articles

Related Articles

Python – K difference index pairing in list

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 31 Dec, 2019

Sometimes while programming, we can face a problem in which we need to perform K difference element concatenation. This problem can occur at times of school programming or competitive programming. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension + zip()
Combination of above functionalities can be used to solve this problem. In this, we iterate the list using list comprehension and formation of pairs using zip().




# Python3 code to demonstrate working of
# K difference index pairing in list
# using list comprehension + zip()
  
# initialize list 
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize K
K = 3
  
# K difference index pairing in list
# using list comprehension + zip()
res = [i + j for i, j in zip(test_list, test_list[K :])]
  
# printing result
print("List after K difference concatenation is : " + str(res))

Output :

The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after K difference concatenation is : ['GI', 'FS', 'GB', 'IE', 'SS', 'BT']

 

Method #2 : Using map() + concat()
The combination of these functions can also perform this task. In this traversal logic is done by map() and concat performs the task of pairing. It’s more efficient than above method.




# Python3 code to demonstrate working of
# K difference index pairing in list
# using map() + concat
import operator
  
# initialize list 
test_list = ["G", "F", "G", "I", "S", "B", "E", "S", "T"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize K 
K = 3
  
# K difference index pairing in list
# using map() + concat
res = list(map(operator.concat, test_list[:-1], test_list[K:]))
  
# printing result
print("List after K difference concatenation is : " + str(res))

Output :

The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after K difference concatenation is : ['GI', 'FS', 'GB', 'IE', 'SS', 'BT']


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!