##### List of lists - merge sublists with common elements
 List of lists - merge sublists with common elements medatib531 Silly Frenchman Posts: 28 Threads: 13 Joined: Mar 2020 Reputation: May-09-2021, 02:29 AM Assume I have list1 as follows: `list1 = [['a','b'],['c','d'],['b','e'],['f','g'],['a','h'],['i','c']]`I want to merge the sublists that have common elements, so based on the above example the resulting list will be `list2 = [['a','b','e','h'],['c','d','i'],['f','g']]`I could do things like parse each element separately and do comparisons all over etc. but the input list can be pretty long (maybe many hundreds or even millions of elements overall) Is there an efficient way to do this in python? Reply Posts: 3,034 Threads: 42 Joined: Jan 2018 Reputation: May-09-2021, 07:49 AM (This post was last modified: May-09-2021, 07:53 AM by Gribouillis.) This is a version of the problem of finding the connected components of a graph. One approach would be to use a library that already has a function to do that, such as networkx. ```>>> import networkx as nx >>> g = nx.Graph() >>> ipath = [['a','b'],['c','d'],['b','e'],['f','g'],['a','h'],['i','c']] >>> for p in ipath: ... g.add_edges_from(zip(p, p[1:])) ... >>> for c in nx.connected_components(g): ... print(c) ... {'e', 'h', 'a', 'b'} {'i', 'c', 'd'} {'g', 'f'}``` Reply

 Possibly Related Threads… Thread Author Replies Views Last Post I cannot delete and the elements from the list quest 4 488 May-11-2021, 12:01 PM Last Post: perfringo Take first Elements of sublists quest 2 265 Apr-26-2021, 11:32 AM Last Post: buran Find Common Elements in 2 list quest 4 467 Apr-14-2021, 03:57 PM Last Post: quest Sort List of Lists by Column Nju 1 369 Apr-13-2021, 11:59 PM Last Post: bowlofred Sorting Elements via parameters pointing to those elements. rpalmer 3 527 Feb-10-2021, 04:53 PM Last Post: rpalmer Group List Elements according to the Input with the order of binary combination quest_ 19 1,180 Jan-28-2021, 03:36 AM Last Post: bowlofred How to print multiple elements from multiple lists in a FOR loop? Gilush 6 567 Dec-02-2020, 07:50 AM Last Post: Gilush Adding List Element if Second part of the List Elements are the Same quest_ 3 541 Nov-25-2020, 04:33 PM Last Post: bowlofred Creating list of lists from generator object t4keheart 1 497 Nov-13-2020, 04:59 AM Last Post: perfringo How do i make a new lists out of an list ozezn1 1 424 Oct-28-2020, 10:19 PM Last Post: Gribouillis

Forum Jump:

### User Panel Messages

##### Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020