The answer has a lot to do with the assumption that the lists have the same number of values or not.
If they have the same number of elements , the answer has been given to you by the problem you have in this statement: contadorIndice = len(lista1) + len(lista2)
. contadorIndice
is the variable that you will use to iterate "up", the problem is that in your example the value contadorIndice
will be 6, then when the iteration reaches 4 the error will appear, simply because the lists have 3 elements only ( lista1[contador]
). The solution is simple, just iterate to the length of any of the lists, no matter which, in this case are the same, for example: while(contador <len(lista1))
On the other hand, if the lists do not have the same logic , the problem is a little more complex. To begin with, one should define what should be done in these cases, if the idea is to keep a list that combines only one element of the other, the iteration should be done up to contadorIndice = min(len(lista1),len(lista2))
that is to say the length of the list more girl. If, on the other hand, we want the final list to be the sum of both lists, we must make some additional modifications and here we should iterate up to contadorIndice = max(len(lista1),len(lista2))
. As an example of the latter, this would be the code:
def unir_listas_alterno(lista1,lista2):
nuevaLista = []
contadorIndice = max(len(lista1),len(lista2))
contador = 0
while(contador < contadorIndice):
if len(lista1) > contador:
nuevaLista.append(lista1[contador])
if len(lista2) > contador:
nuevaLista.append(lista2[contador])
contador+=1
return nuevaLista
lista1 = ["a","b","c"]
lista2 = [1,2,3,4]
print(unir_listas_alterno(lista1,lista2))
Of course there are much more compact ways of solving these situations, for example the use of zip_longest
that basically will be combining element by element setting tuples of type ("a", 1), (b, "2"), ("c", 3), (None, 4)
that then you simply have to "flatten" to turn everything into a list.
from itertools import izip_longest
lista1 = ["a","b","c"]
lista2 = [1,2,3, 4]
lista_final = [e for l in list(izip_longest(lista1, lista2)) for e in l if e]
print(lista_final)
> ['a', 1, 'b', 2, 'c', 3, 4]