# Merge python lists in a specific order/sequence

I'm trying to make two lists of the sort:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12] list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]

into

list_both= ["onetothree",1,2,3,"fourtosix",4,5,6...]

This is just a way to describe my problem. I need to do this with all the elements in list_numbers & list_letters. The number or elements in list_numbers will always be dividable by the amount of elements in list_letters so theres no need to worry about "crooked data".

After searching for a good three hours, trying with **many** different kinds of "for" and "while" loops and only getting python 2.x questions, bad results and syntax errors, I thought I'd maybe deserve to post this question.

## Answers

Hacky, but it'll get the job done

>>> list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12] >>> list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"] >>> list(itertools.chain.from_iterable(zip(list_letters, *zip(*[list_numbers[i:i+3] for i in range(0, len(list_numbers), 3)])))) ['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]

Or, the cleaner version:

>>> answer = [] >>> i = 0 >>> for letter in list_letters: ... answer.append(letter) ... for j in range(3): ... answer.append(list_numbers[i+j]) ... i += j+1 ... >>> answer ['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]

Of course, if you don't have sufficiently many entries in list_numbers, you this will burn you

try this:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12] list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"] list_both=[] c=1 for n in range(len(list_letters)): list_both.append(list_letters[n]) list_both[c+n:c+n]=list_numbers[c-1:c+2] c+=3 print(list_both)