0

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

3 Answers3

2

Just use extend for each of the lists you want to add on:

list1.extend(list2)
list1.extend(list3)
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
2

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.

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
1

You can extend one of the lists with the addition of the other two:

list1 = [ 'a', 'b', 'c']
list2 = [ 'd', 'e', 'f']
list3 = ['g', 'h', 'i']

list3.extend(lis1 + list2)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139