If you are looking for a list of the size of the largest but with the elements that share the index added, you can make a slight modification to your code:
mayor, menor = (lista1, lista2) if len(lista1) > len(lista2) else (lista2, lista1)
lista3 = []
for i, _ in enumerate(mayor):
if i + 1 > len(menor):
lista3.append(mayor[i])
else:
lista3.append(mayor[i] + menor[i])
print(lista3)
Basically:
- We first establish which is the major list to iterate through the same
- In the cycle if the index exceeds the length of the minor list, we simply copy the element of the largest, but add the element corresponding to the index of the two lists
Note: In for i, _ in enumerate(mayor):
we use _
to ignore one of the elements received from enumerate
, just the one we will not use, it is a good practice to do so.
Additionally, a simpler way to solve this problem is:
from itertools import zip_longest
result = [sum(n) for n in zip_longest(lista1, lista2, fillvalue=0)]
print(result)
Using zip_longest
, which is nothing more than zip
normal but that takes into account which is the largest list, what we achieve is to combine both lists creating "couples" and adding a 0 for the elements of the smallest list ( fillvalue=0
), we would have something like this:
[(1, 5), (2, 6), (3, 7), (4, 8), (5, 0), (6, 0)]
Thus, we can apply a sum
on each tuple without problems obtaining the expected result.