Related Articles
Python – K difference index pairing in list
• 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']
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up