Traverse two arrays in parallel

Asked

Viewed 1,459 times

1

Want to traverse two arrays in parallel by adding : among them:

Arrays

NOME = ['CARLOS','JOAO','PEDRO']

IDADE ['30','25','22']

DESIRED OUTPUT

CARLOS:30
JOAO:25
PEDRO:22

Trying

rows = len(NOME)
for i in range(rows):
    print(str(NOME[i]+":"+IDADE))

ERROR

Typeerror: cannot concatenate 'str' and 'list' Objects

2 answers

5


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.

  • 1

    Thank you very much for the explanation and examples, it was very didactic!

2

The error occurs precisely because you are trying to add up two incompatible things. You cannot add up a list to a text. But what you want is not even this, you want to add an element of a list to the element of another list, and this is not happening.

You take elements from each of the lists and do not take an element from a list and the entire list from the other side. There’s no reason to complicate the attempt if you want something so simple.

nomes = ['CARLOS', 'JOAO', 'PEDRO']
idades = ['30', '25', '22']
rows = len(nomes)
for i in range(rows):
    print(nomes[i] + ":" + idades[i])

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

There’s a way to make it a little better, but I think it’s still raw to see other ways. Seeing another way now will make decorate cake recipe but not learn how to solve a problem simply. I just made the code more readable and took what it didn’t mean there.

The form presented is not idiomatic for Python, but it is simple and efficient, so I opted for this form. In general, those who use Python do not value efficiency, perhaps because most people who choose this language are not actual programmers. Many adopt it for being a simple language and not for being efficient, and not because it would be the best choice for the problem. But not everyone makes this mistake, some choose knowing that they are just solving the simple problem and a language of script is more appropriate.

Note that I am talking about efficiency and not speed (although it is almost certain that it will be faster the way I did after all there is no extra operation, even done in C is something unnecessary, just do not guarantee because the range() is also an unnecessary abstraction and Python makes allocations where it shouldn’t in several cases), this is about not doing unnecessary things.

In this case the algorithm of a zip will allocate memory without need, what the problem asks is too simple to use a swipe. One of the problems of language that gives something ready is that people don’t realize that it can be very inefficient. Anything that does something not necessary should not be used, even if it seems short and cute. Of course what I am saying can be criticized, this is the vision of a software developer and not creator of script.

I defend my answer as simpler for those who are starting and teach more how to make the algorithm as a mechanism and why it gave the error in question, without abstractions, mainly unnecessary (bobbing up the range() should not be used). Although the hkotsubo response is more complete and idiomatic for those who have already passed this stage. If you were to do choreo even all this would be wrong, you would not have two lists but a list of objects with all the necessary data.

  • That, I would like to go through the two lists in parallel, each row of one corresponds to the line of the other, but gave this error when I used your script: Typeerror: range() integer end argument expected, got list.

  • Do not: https://ideone.com/DQDV6i

  • Oops, it worked now, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.