Where is 'breed' defined?

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`)

you define the breed variable here:

for breed in dog_breeds:

python will now assign the items of the list to the breed variable (one at a time). Python does a lot of heavy lifting for you

16 Likes

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 iterable collection.

(What is an iterable? Easy. Something that you can do for-in with! :slight_smile: )

8 Likes

Thank you all,

This made a lot sense now, it was confusing at first but your explanations helped.

Thanks :slight_smile:

How does python know that what “breed” as it was not specifically defined…“def dog_breed”

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

“dog_breed” v “breed”

11 Likes

you define breed here:

for breed in dog_breeds:

python will assign the values from the list to breed (or whatever variable name you decide to give this variable)

17 Likes

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

You won’t know how much relief you caused with this response. I have struggled with this for looooonnngggg (even as simple as it seems

But if I use anything other than “breed” (just to chek this out I tried “bred” and “breeds”) I get this error:

Traceback (most recent call last):
File “script.py”, line 3, in
print(breed)
NameError: name ‘breed’ is not defined

So the explanation given by everyone does not hold up. Python doesn’t assign those values and throws back an error.

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.

in other words, this won’t work:

for bred in dog_breeds:
print(breed)

but this will:

for bred in dog_breeds:
print(bred)

in the first example, i “forgot” to change ‘breed’ into ‘bred’ when i print it…

1 Like

I am asking myself the same question?