# Rearranging elements of a list

I have a list:

oldList = {"a-1", "b", "c", "a-2", "d", "e", "f", "a-3", "w"}


and would like to get the following list:

newList = {{a-1,b}, {a-1,c}, {a-2,d}, {a-2,e}, {a-2,f}, {a-3,w}}


I see that there was a similar but not identical question was posed here four years ago. I started by using StringMatchQ and Position to find the position of the elements that contain "-" and then Complement to find which elements need to have the terms containing "-" affixed to them. But Insert doesn't seem to be very flexible and I'd like to avoid a bunch of For loops.

• Don't you think you could modify answers to your previous questions to apply them here? – jjc385 Dec 4 '17 at 4:47

Join @@ (Thread[{#, {##2}}] & @@@ Split[oldList, StringFreeQ[#2, "a"] &])


{{"a-1", "b"}, {"a-1", "c"}, {"a-2", "d"}, {"a-2", "e"}, {"a-2", "f"}, {"a-3", "w"}}

Also,

Flatten[Thread[{#, {##2}}] & @@@ Split[oldList, StringFreeQ[#2, "a"] &], 1]


{{"a-1", "b"}, {"a-1", "c"}, {"a-2", "d"}, {"a-2", "e"}, {"a-2", "f"}, {"a-3", "w"}}

• My mistake, I should have made it clear that oldList is a list of strings. Both of your solutions lead to {{"a-1", "b"}, {"a-1", "c"}, {"a-1", "a-2"}, {"a-1", "d"}, {"a-1", "e"}, {"a-1", "f"}, {"a-1", "a-3"}, {"a-1", "h"}, {"a-1", "w"}, {"a-1", "z"}} – Suite401 Dec 4 '17 at 4:11
• @Suite401, please see the updated version. – kglr Dec 4 '17 at 5:06
• Yes. Thanks /@you, kglr, swish. – Suite401 Dec 4 '17 at 5:23
• And one final generalization question, and i'll let go of this issue; – Suite401 Dec 4 '17 at 6:34
• I will post it as a new question, and please tell me what the best way to handle these situations, so as not to annoy people. – Suite401 Dec 4 '17 at 6:44

Try this:

Flatten[
SequenceCases[oldList,