Using for loop on a list with multiple data types

After searching a bit and not finding an answer, here I am with my question.

The example given in the for loops chapter was this:

dog_breeds = [‘french_bulldog’, ‘dalmation’, ‘shihtzu’, ‘poodle’, ‘collie’]
for breed in dog_breeds:
print(breed)

Now, my question is, say we have a list containing names and ages of people, such as:

my_list = [‘Pam’, 22, ‘George’, 44, ‘Robert’, 35] and so on…

Now, can I use a for loop to loop through the ages (integers) and return the age values? If yes, then how do I do that ?

1 Like

Now, can I use a for loop to loop through the ages (integers) and return the age values? If yes, then how do I do that ?

You can, normally if you were to have people with ages values assigned to them you would do it in a dictionary { }.

However, for the sake of argument, if somebody gave you this in a list format, you can either target the numbers with a conditional for type within the loop:
if type(num) == int.

The more difficult example is if for example there’s three values, name, age, and a third integer, but you can use strides in that case:

If you know it’s going to be in constant intervals (e.g. every second value), you can change the stride of the for-loop

list = ['b', 'r', 'e', 'a', 'd']
for i in range(0, len(list), 2):
     print(list[i])
# b        #(index 0)
# e        #(index 2)
# d        #(index 4)
1 Like

Great !!! Thanks a lot for helping me out. This surely clears the doubt.

1 Like