Can someone please explain why the below "breed’ term yields all the names when nothing in the code is identified or saved as a variable called “breed”?
dog_breeds = ['french_bulldog', 'dalmatian', 'shihtzu', 'poodle', 'collie']
for breed in dog_breeds:
print(`breed`)
In a for-in expression, for item in collection, item is the iteration variable. It is successively assigned the value of each element in the iterablecollection.
(What is an iterable? Easy. Something that you can do for-in with! )
I was going to ask just this question. I have been coming across loop on the side and this has been a major headache for me. Reading the response from mtf make me feel good
If you use your code editor’s search/highlight functionality and type in “breed” then presumably you are likely mentioning it in two places. One place where you are defining it, one place where you are using it.
dog_breeds = [‘french_bulldog’, ‘dalmatian’, ‘shihtzu’, ‘poodle’, ‘collie’]
for breed in dog_breeds:
print(breed)
the ‘breed’ portion in “for breed in dog_breeds:” is a temporary variable that is defined by each iteration of the list. Meaning, at first pass, the variable ‘breed’ takes the value of the first index in the list -french_bulldog in this case. Then the “print(breed)” instruction prints the value of the temporary variable, french_bulldog. Then the loop proceeds to each other item in the list until it reaches the last index.
I’m new to programming too, and struggling with loops as well; the above is my very newby understanding of a simple loop.
I’d be a little careful about referring to it a temporary variable since after the loop breed is still referencing the last object from whatever iterable the loop was stepping through. It’s not in a different scope and can still be accessed.
dog_breeds = ["french_bulldog", "dalmatian", "shihtzu", "poodle", "collie"]
for breed in dog_breeds:
print(breed)
print(breed)
Out:
french_bulldog
dalmatian
shihtzu
poodle
collie
collie
Here, breed is temporary variable assigned the value of an item(which means it teporarily holds a copy of the list item value) each time the for loop iterates.
One thing to notice is even if the value of breed changes (which is in fact of copy value of the list item), there’s no affect in the original list
The iterable can be literally any name you choose. The word “breed” is used in the example because it makes the most sense in this case. However, you could use the standard “i” for the iterable instead:
for i in dog_breeds:
print(i)
french_bulldog
dalmatian
shihtzu
poodle
collie
i is generally used as abbreviation for index, so not sure that is the best fit here. Giving a descriptive name for what the values are going to be is better
Think of ‘breed’ as a container with no intrinsic value. ‘For’ loop assigns the values from the list ‘dog_breeds’ to the container and the print command prints out whatever is stored in that container.