When it is required to cross join every ‘K’th element, a method is defined that uses iteration and fetches the index as output.
Example
Below is a demonstration of the same −
def merge_pair_elem(my_list_1, my_list_2, K): index_1 = 0 index_2 = 0 while(index_1 < len(my_list_1)): for i in range(K): yield my_list_1[index_1] index_1 += 1 for i in range(K): yield my_list_2[index_2] index_2 += 1 my_list_1 = [24, 13, 82, 22, 65, 74] my_list_2 = [55, 63, 17, 44, 33, 15] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) K = 1 print("The value of K is :") print(K) my_result = [element for element in merge_pair_elem(my_list_1, my_list_2, K)] print("The result is :") print(my_result)
Output
The first list is : [24, 13, 82, 22, 65, 74] The second list is : [55, 63, 17, 44, 33, 15] The value of K is : 1 The result is : [24, 55, 13, 63, 82, 17, 22, 44, 65, 33, 74, 15]
Explanation
A method named ‘merge_pair_elem’ is defined that takes two lists and a ‘K’ value as parameter, and returns specific index as output.
Outside the method, two lists of integers are defined and are displayed on the console.
A value for ‘K’ is defined and is displayed on the console.
A list comprehension is used to iterate over the elements and the method is calling by passing the required parameters.
This is converted to a list, and is assigned to a variable.
This is the output that is displayed on the console.