Multi-entry loop for list - Python

Asked

Viewed 254 times

-1

I have a list of several tuples inside, and within tuples various elements. I need to scan all tuples on the list to capture an element that is inside each of these tuples. How can I do this?

The structure is below:

Created variable / Type:list / Size: 10 When opening the list: Contents: 0 / Type: Tuple / Size: 5 -> being: 2 Str and 3 Int

I want to capture one of the data type Int.

1 answer

1

Normally we use the for to iterate over a list.

lista = [1, 2, 3]

for numero in lista:
    print(numero)

The exit will be:

1
2
3

A tuple (as well as a list) can be accessed by the index of its element

tupla = ("John", "Doe", 40)

nome = tupla[0]
sobrenome = tupla[1]
idade = tupla[2]

So we have:

>>> print(nome)
John
>>> print(sobrenome)
Doe
>>> print(idade)
40

Togetherness

lista_com_tuplas = [("John", "Doe", 40), ("Joao", "Silva", 30)]

for tupla in lista_com_tuplas:
    nome = tupla[0]
    sobrenome = tupla[1]
    idade = tupla[2]
    print(f"{nome} {sobrenome} tem {idade} anos.")

Exit

John Doe tem 40 anos.
Joao Silva tem 30 anos.

I hope I’ve helped.

  • It helped, but what I need is to take only one of the elements of each tuple and add up tds.... There are several Tuples in which I need to capture 1 element of each...

  • Can you follow from what I’ve shown or need help yet?

  • I couldn’t do it, Paulo. I did one inside another for, but it’s iterating the first item inside Tupla (which is a Str), but I need it to return the fifth element of Tupla, which is an Int.

  • Paulo, I got it now!!! I made a junction of what you answered and it worked!!! Thank you very much! I am new to the programming and this was my first post here and was solved thanks to your contribution!!! I really appreciate your help!!! Abs and success!

  • Good @Darthgaino one step at a time

Browser other questions tagged

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