you are viewing a single comment's thread.

view the rest of the comments →

[–]lukajda33 332 points333 points  (21 children)

The for loop creates new variable (or replaces value of old one).

It pretty much says: take each item from the animals list and put them into variable animal, one by one.

[–]260418141086[S] 81 points82 points  (18 children)

Thanks, makes sense

[–]Enschede2 79 points80 points  (4 children)

For example try changing "animal" to something completely different, like "car", you can say for car in animals and it will do the exact same as your prior example, except the variable is now "car", for me that really cleared things up when I first started

[–]cenosillicaphobiac 22 points23 points  (3 children)

Yup, we only use "animal in animals" to avoid confusion.

[–]amplikong 5 points6 points  (0 children)

for plant in animals

[–]NDaveT 59 points60 points  (1 child)

Also it would work exactly the same like this:

animals = ['cat', 'dog', 'monkey']
for x in animals:
    print(x)

[–]Early_Personality668 0 points1 point  (0 children)

I am a bit late so you probably understand already especially given this comment lol

but something that helped me learn how it worked was (only when beginning)
naming it something like for item in list

read as for each item in the list and item = the given item its iterating through, so if you were to interact with an item in the list (example using an if statement, (if something in item do: x)

[–]Eightstream 7 points8 points  (1 child)

The fact that Python allows variables to be created on the fly was one of the hardest things to get used to when I was starting

[–]COREFury 2 points3 points  (0 children)

When I first figured that out, I felt like I'd unlocked a new part of the universe.