Federico Leoni Federico Leoni - 5 months ago 13
Python Question

Extend: merge strings on a list from two other lists at the same time

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 two lists, 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']]


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, and this is the easiest example, think to something more complex like:

list1.extend(('test', list2, fetch[0], list3, etc, etc, etc))


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'.

Answer

If you're looking for a clean way of extending a single list with N number of other lists, it's as simple as that:

my_list = ['a', 'b', 'c']
for other_list in (some_iterable, some_other_iterable, another_iterable):
    my_list.extend(other_list)

I can't think of any more reasonable solution than that.

Comments