You can correlate the elements of lists lista1
and lista2
through the function zip
. In addition, you can concatenate lists by using the +
operator. So if you create a new list - using list comprehensions - where each element is e1[:2] + e2 + e1[-1:]
You get what you want:
>>> lista1 = [['carlos','10','cenouras','carro','agora'],['duarte','34','couves','bus','agora']]
>>> lista2 = [['11:30', '12:00'],['13:00', '13:30']]
>>> listaNova = [e1[:2] + e2 + e1[-1:] for e1, e2 in zip(lista1, lista2)]
>>> listaNova
[['carlos', '10', '11:30', '12:00', 'agora'], ['duarte', '34', '13:00', '13:30', 'agora']]
(Note that I used e1[-1:]
instead of simply e1[-1]
because I want a list with an element, not just the element)
If you want to do it "extensively" (i.e. using loops, append
and extend
), it would look like this:
listaNova = []
for e1, e2 in zip(lista1, lista2):
item = []
listaNova.append(item) # append acrescenta um item na lista
item.extend(e1[:2]) # extend acrescenta os itens do argumento na lista
item.extend(e2)
item.append(e1[-1]) # como é um único elemento, pode usar append
Finally, if you want to avoid zip
, you can make a normal loop over the indexes of lists (be careful that lists have equal size):
listaNova = []
for i in range(len(lista1)): # i vai de 0 a "tamanho da lista" - 1
item = []
listaNova.append(item)
e1 = lista1[i]
e2 = lista2[i]
item.extend(e1[:2])
item.extend(e2)
item.append(e1[-1])
But notice how extensive the code is, while the first method does the same thing using a single line of code ... As you master these concepts (especially list comprehension, one of the most powerful features of language ) become accustomed to using them instead of more verbose constructs, when appropriate.