Python | Merge overlapping part of lists

Sometimes, while working with Python lists, we can have a problem in which we have to merge two list’s overlapping part. This kind of problem can come in day-day programming domain. Let’s discuss a way in which this problem can be solved.

Method : Using generator + next() + list slicing
This method can be employed to solve this task. In this, first, we iterate a variable from rear end of one of list, and get the slice of rear end of first list till match of initial slice of second list. Then, we get the first such overlapping( max overlap ) using next() and then we join the remaining part using list slicing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Merge overlapping parts of list
# using generator + next() + list slicing
  
# initialize lists
test_list1 = [4, 5, 7, 9, 10, 11]
test_list2 = [10, 11, 16, 17]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Merge overlapping parts of list
# using generator + next() + list slicing
temp = (i for i in range(len(test_list2), 0, -1) if test_list2[:i] == test_list1[-i:])
temp2 = next(temp, 0)
res = test_list1 + test_list2[temp2 : ]
  
# printing result
print("List after overlapping merge is : " + str(res))

chevron_right


Output :

The original list 1 is : [4, 5, 7, 9, 10, 11]
The original list 2 is : [10, 11, 16, 17]
List after overlapping merge is : [4, 5, 7, 9, 10, 11, 16, 17]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.