If you want to scroll through two lists at the same time, you can use function zip
:
nomes = ['CARLOS','JOAO','PEDRO']
idades = ['30','25','22']
for nome, idade in zip(nomes, idades):
print('{}:{}'.format(nome, idade))
In this case, with each iteration of the for
, the variables nome
and idade
will have a list element nomes
and idades
. The exit is:
CARLOS:30
JOAO:25
PEDRO:22
This works well if the two lists have the same size. But if they have different sizes, the for
is closed as soon as the smallest of the sequences ends. For example, if the lists are:
nomes = ['CARLOS','JOAO','PEDRO', 'FULANO SEM IDADE']
idades = ['30','25','22']
The output is the same as the previous code.
If you want to show all names, even if the list of names is longer than the ages, you can use the method zip_longest
of module itertools
:
import itertools
nomes = ['CARLOS','JOAO','PEDRO', 'FULANO SEM IDADE']
idades = ['30','25','22']
for nome, idade in itertools.zip_longest(nomes, idades, fillvalue=''):
print('{}:{}'.format(nome, idade))
In the case, fillvalue
defines the value that will be used when a list is larger than another and there is no corresponding element. In the example above, one of the names will not have the corresponding age, so I set the value ''
(an empty string) to be shown instead of the age. The output is:
CARLOS:30
JOAO:25
PEDRO:22
FULANO SEM IDADE:
Note also that I have changed the names of the lists. After all, if it is a list containing several names, it makes more sense to call it nomes
(plural), than NOME
(singular). It may seem like a minor detail, but give better names - for variables, functions, modules, etc - help a lot when programming.
Thank you very much for the explanation and examples, it was very didactic!
– Luis Henrique