What is the type of a temporary variable in a for loop?

In a for loop, what type of variable is the temporary variable? What does it appear to have two different types of values? Ex: for i in dog_breeds: print(i)

i seems to have an int value first (number of times), then a string value(dog breed that gets printed).

variables don’t have types, values do
the values come from whatever you are iterating through

your observation about the type changing is probably wrong in some way. maybe you changed your code so that your loop was iterating through different things


What I mean in the above example is the temporary variable i seems to first be a number (for i in …) then a string (print(i)) - is that what is going on?

It is whatever you last assigned to it. What’s going on is probably that you either meant a different value, or you assigned something else to it, or even that you iterated through something containing different kinds of values.

If you iterate through strings then your loop variable will refer to strings.

I think you’re just misunderstanding how the for ... in loop works. i is assigned each element of the dog_breeds list (assuming it is a list) one at a time. i is NOT assigned the index of the element. The value of i will be of whatever type each element of the dog_breeds list is when assigned. Look at this example:

dog_breeds = ['doberman', 'collie', 'daschhund', 7, False]

for i in dog_breeds:
    print('value: {}  type: {}'.format(i, type(i)))


value: doberman type: <class ‘str’>
value: collie type: <class ‘str’>
value: daschhund type: <class ‘str’>
value: 7 type: <class ‘int’>
value: False type: <class ‘bool’>


Thanks, this was really helpful!