Given two lists of equal length, l1
and l2
, both consisting of sublists that are either empty or non-empty – but corresponding sublists are never non-empty – the task is to consolidate or “collapse” the lists to make a new list newList
where
- if the
n
th element ofl1
is an empty list, but the same element ofl2
is not, thennewList[[n]]
takes that sublist froml2
; - if the
n
th element ofl1
is non-empty, but the same element ofl2
is an empty list, thennewList[[n]]
takes that sublist froml1
; - if the
n
th element of bothl1
andl2
are empty lists, then so will be the same element ofnewList
I have some working code for such a function, but I’m curious if there is a simpler or faster way to execute this sort of task. Perhaps I’ve overlooked a built-in method? Any suggestions appreciated (even for making the question title more concise).
Collapse[l1_List, l2_List] := Module[ {newList, n, commonLength}, newList = {}; If[ Length[l1] === Length[l2], commonLength = Length[l1]; n = 1; While[ n <= commonLength, If[ (l1[[n]] === {}) && (l2[[n]] =!= {}), AppendTo[newList, l2[[n]]], If[ (l1[[n]] =!= {}) && (l2[[n]] === {}), AppendTo[newList, l1[[n]]], If[ (l1[[n]] =!= {}) && (l2[[n]] =!= {}), Print["Lists are not collapsible"], AppendTo[newList, {}] ]; ]; ]; n++ ];, Print["Lists are incompatible"]; ]; If[ newList =!= {}, Return[newList] ]; ];
Test cases
Collapse[{{}}, {{}}] (* {{}} *) Collapse[{{}}, {{1}}] (* {{1}} *) Collapse[{{}, {1}, {}}, {{}, {}, {a}}] (* {{}, {1}, {a}} *) Collapse[{{}}, {{}, {}}] (* Lists are incompatible *) Collapse[{{1}}, {{a}}] (* Lists are not collapsible *)