Extending two lists at once

Viewed 93

I have two lists (list_1,list_2) and a function which returns two lists (list_1_f, list_2_f) and I would like to add the items of list_1_f to list_1 and the items of list_2_f to list_2:

def lists():
    list_1_f = [10,10,10]
    list_2_f = [20,20,20]    
    return list_1_f,list_2_f

list_1, list_2 = [1,1,1], [2,2,2]

I always will have 2 original lists and the extension is going to be done just for another two extra lists, there is no other possibility. So that at the end I would have two lists with the original items plus the ones got from the function, and the output would be:

list_1 = [1,1,1,10,10,10]
list_2 = [2,2,2,20,20,20]

I have tried the following lines using extend function but none works:

list_1.extend([]), list_2.extend([]) = lists()
list_1.extend(), list_2.extend() = lists()
list_1.extend, list_2.extend = lists()

I could always do the following:

list_1a, list_2a = lists()
list_1.extend(list_1a)
list_2.extend(list_2a)

But I was wondering if it is even possible to make the extension without having to create two intermediate lists.

3 Answers

For handling multiple lists you should be using nested lists instead. Say for instance you initially have this nested list:

l =  [[1,1,1], [2,2,2]]

You could zip both nested lists and use map to extend the returned sublists using operator.add :

from operator import add

extended_list = *map(add, *zip(l, lists())),
# ([1, 1, 1, 2, 2, 2], [10, 10, 10, 20, 20, 20])

You can iterate, so you could do something like:

list_1.extend(lists()[0])
list_2.extend(lists()[1])

This works but is not very readable. If you make a list of lists you want to append tolist_of_lists=[list_1,list_2] then you can do the following:

for n in list_of_lists:
  list_of_lists[n].extend(lists()[n])

Hope it helps!

You can extend one list with another with just summarizing them:

[1,2,3] + [4,5,6]

[1, 2, 3, 4, 5, 6]

So your code may looks like this:

def lists():
    list_1_f = [10,10,10]
    list_2_f = [20,20,20]    
    return list_1_f,list_2_f

list1 = [0]
list2 = [999]

list1 = list1 + lists()[0]
list2 = list2 + lists()[1]

print(list1, list2)

[0, 10, 10, 10] [999, 20, 20, 20]

Related