Associate two lists in python

2

Associate two lists, a list with car name and another list of colors and each one containing n elements:

listaCarros = ["gol","uno","corsa","palio","idea"]
listaCores = ["branco","verde","preto","cinza","azul"]

with the output in this format:

"Goal is white"

I did the following:

n=0

while n <= 5:

    print("\nO", end=' ')
    print(listaCarros[n],end=' é ')
    print(listaCores[n])
    n = n + 1

It worked, but this message appeared:

Traceback (most recent call last): "file path" line 286, in     print (carlist [n], end = 'é') IndexError: list index out of range

Would you have a better way to do this?

    
asked by anonymous 23.09.2017 / 17:58

1 answer

5

The condition <= 5 is wrong, because if the lists have 5 elements they only have between 0 and 4 indexes (since these start at 0), you try in this version of code while n < 5 , or better while n < len(listaCarros): .

That said, here's a more #

listaCores = ['azul', 'vermelho', 'verde', 'laranja', 'branco', 'preto']
listaCarros = ['mazda', 'toyota', 'honda', 'pegeot', 'mercedez', 'BMW']
text = ''
for carro, cor in zip(listaCarros, listaCores):
    text += '\nO {} é {}'.format(carro, cor)
print(text)

DEMONSTRATION

To do what you were doing (with while) using this example (you need to be careful that the lists have the same number of elements, or build the cycle based on the list with the fewest elements):

listaCores = ['azul', 'vermelho', 'verde', 'laranja', 'branco', 'preto']
listaCarros = ['mazda', 'toyota', 'honda', 'pegeot', 'mercedez', 'BMW', 'saf', 'safs']

n = 0
text = ''
min_list = min(len(listaCores), len(listaCarros))
while n < min_list: # fazes isto caso nao tenhas a certeza que as listas tem o mesmo num de elementos
    text += '\nO {} é {}'.format(listaCarros[n], listaCores[n])
    n += 1
print(text)

DEMONSTRATION

    
23.09.2017 / 18:54