Federico Leoni Federico Leoni - 2 years ago 67
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:



['a', 'b', 'c', 'g', 'h', 'i']

Adding two lists:


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:
for l2 in list3:

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 Source

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):

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download