I have 3 different lists and I need to merge them. It is easy when you need to extend a list with just an element or adding an inteire list. But with more lists or adding a variable in the middle, it seems impossible.
list1 = [ 'a', 'b', 'c']
list2 = [ 'd', 'e', 'f']
list3 = ['g', 'h', 'i']
Adding just one list:
list1.extend(list3)
Return:
['a', 'b', 'c', 'g', 'h', 'i']
Adding two lists:
list1.extend((list2,list3))
Return two lists inside another list:
['a', 'b', 'c', ['d', 'e', 'f'], ['g', 'h', 'i']]
Adding two list with operator '+':
list1.extend((list2 + list3))
Returns
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
but if you need to do something like:
list1.extend(('test' + list2 + fetch[0] + list3 + etc, etc, etc))
will not works.Can't concatenate.
A temporary solution adding a loop could be:
for l1 in list2:
list1.extend(l1)
for l2 in list3:
list1.extend(l2)
to finally have:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
Clearly a waste of lines and cycles
Is there a more efficient way to archive that without using external modules?
EDIT: the example of simple lists is just to understand what basically I need. The real problem is adding string or number or index on a single line of '.extend'.
SOLVED:
Wayne Werner drive me to the right direction to concatenate different type of elements.
list1 = [ 'a', 'b', 'c']
list2 = [ 'd', 'e', 'f']
list3 = ['g', 'h', 'i']
for other_list in (['test'], str(1), list2[2], list2[1]):
list1.extend(other_list)
Result:
['a', 'b', 'c', 'test', '1', 'f', 'e']