Related Articles
Python | Merge overlapping part of lists
• Last Updated : 05 Sep, 2019

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.

 `# 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))`
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]
```

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