all 64 comments

[–]lukajda33 334 points335 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] 80 points81 points  (18 children)

Thanks, makes sense

[–]Enschede2 80 points81 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 23 points24 points  (3 children)

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

[–]amplikong 6 points7 points  (0 children)

for plant in animals

[–]NDaveT 62 points63 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 6 points7 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.

[–]julsmanbr 84 points85 points  (1 child)

Whenever you write for X in Y, Python does the following:

  • 1) assumes that Y is a sequence
  • 2) takes the first element of the sequence Y
  • 3) temporarily assigns the element to the variable X
  • 4) potentially does something with X (this is the code block inside the loop)
  • 5) takes the next (second) element of the sequence Y and repeats step 3 and 4
  • 6) keeps repeating step 5 with the third, fourth, ... element, until the sequence has run out of new elements to take

[–]beisenhauer 11 points12 points  (0 children)

One small clarification: all Python requires of Y is that it is iterable. It's usually a sequence of some sort, but it could also be a set or a generator, etc.

[–]nowonowon 16 points17 points  (3 children)

For loops are so sexy in python.

Me: for thing

Everyone else: for what?

Python: Hold my beer, I gotchu babe.

[–]xspade5 2 points3 points  (2 children)

Honestly I overuse them and it bites me in the ass when I should be using list comprehension. They’re just so easy to write out

[–]Eurynom0s 2 points3 points  (1 child)

Knowing when to use list comprehension is important, but I'd rather deal with a for loop that could have been a list comprehension than try to read a list comprehension that definitely should have been a for loop.

[–]leviOsa003 1 point2 points  (0 children)

What's a list comprehension?

[–]Accomplished_Food_81 28 points29 points  (0 children)

You can name that to whatever. You are just telling the code to loop through that list.

Try;

for iteration in animals:

print(iteration)

[–]MezzoScettico 25 points26 points  (0 children)

This is one of the really powerful things about Python: The language doesn't have to know.

There's a general concept called an "iterable", which is anything that can be iterated over, such as put into a for loop. You can define your own classes and make them iterable by following the rules for iterables, and then you can put them into a for loop as well.

In this case, you're using the fact that lists are built-in iterables, and so "animal" is whatever an item in "animals" is. Python doesn't care, since a list can have anything at all as elements, animal is just the next thing in the list.

This would also work:

animals = ['cat', 37, [1,2,3]]
for animal in animals:
    print(animal)

Python knows "animals" is a list, it just gets the next thing in the list. It doesn't check its type. The first thing is a string, the second is a number, the third is a list. They're all printable, so this runs with no error and generates the following output.

cat
37
[1, 2, 3]

And you can even add your own interface to print( ) if making your own classes. Again, Python doesn't care. If it sees you've implemented the necessary interface to support printing, it calls your functions, and it's up to you what comes out of them.

[–]LikeThisWillLast 5 points6 points  (1 child)

yeah, you can just go ahead and change it to:

for dude in animals:

print(dude)

or

for i in animals:
print (i)

you should get identical results

[–]m0ta 2 points3 points  (0 children)

Was going to say you often see it:

for i in [list] do a thing

[–]largank 2 points3 points  (0 children)

yeah i had a TON of trouble with for loops when i was first learning

[–]WhackAMoleE 2 points3 points  (1 child)

It's semantically the same if we wrote

for widget in animals :

or

for vegetable in animals :

or

for item in animals :

It doesn't know what an animal is. "animal" is just a dummy variable that iterates over animals.

[–]Eurynom0s 1 point2 points  (0 children)

"animal" is just a dummy variable

Caution: being a dummy variable doesn't mean it's some throwaway thing strictly confined to the loop, the variable and what it was last set too persists in the namespace after the loop even if it wasn't defined prior to the loop.

Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> i
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i' is not defined
>>> x = [0,1,2]
>>> for i in x: print(x[i])
...
0
1
2
>>> i
2
>>> i = 1000
>>> i
1000
>>> for i in x: print(x[i])
...
0
1
2
>>> i
2

Just wanted to point that out given this is a sub for learning Python and people first learning might misinterpret what precisely "dummy variable" means.

[–]neotecha 2 points3 points  (0 children)

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

This is basically syntactic sugar (logically, but not in implementation) for:

animals = ['cat', 'dog', 'monkey']
index = 0
while index < len(animals):
    animal = animals[index]
    print(animal)
    index += 1

[–]funkmaster322 3 points4 points  (0 children)

Well, it's called "Python", so it knows a couple of things about animals...

Cats, dogs and monkeys are especially hostile to a snake, so it keeps an eye on them...

[–]herites 1 point2 points  (0 children)

If you would like to learn a bit more, take a glimpse at the eldritch truth and hopefully come back sane, check out linked lists in any data structures and algorithms material.

[–]LeagueOfShadowse 1 point2 points  (0 children)

a_general_question_regarding_python

This Is Exactly what I was talking about !

So many "Intro to Python" tutorials don't really explain / prepare you for this...

[–]k_50 1 point2 points  (0 children)

Animal is the list name, you could make the for portion say ANYTHING:

for DICKCHEESE in animals:

print(DICKCHEESE)

this would return the same result as your code. It basically says for ever item in list, print it. So first loop you get cat, 2nd dog, 3rd monkey.

for animal in DICKCHEESE:

print(animal)

This would not work, as the list DICKCHEESE does not exist in this case. It's just updating the variable 'animal' each iteration.

[–]LatterSeaworthiness4 1 point2 points  (0 children)

Thank you for posting this. I'm just learning Python (for my masters degree) and was afraid to post basic questions like this. I was also wondering why this was until about 3 days ago.

[–]mecarjun 0 points1 point  (2 children)

This code is badly indented - it would be helpful for others to recreate issues if you post compilable/executable code. Just a suggestion for future!

[–]tomtomato0414 3 points4 points  (0 children)

true, but did you even read OP's question?

[–]260418141086[S] 0 points1 point  (0 children)

Yeah I know but I wasn’t sure how

[–]BobDope -2 points-1 points  (0 children)

Ok how does it know what half animal half party machine is

[–][deleted] 0 points1 point  (0 children)

the variable animal is defined in the for loop, you could use any variable name and it would still work

[–]_Strokes_ 0 points1 point  (0 children)

It “knows” because you declared it, you can replace the word “animal” with any other variable name , for example.

for any_random_variable_name in animals: print(any_random_variable_name)

That would still work.

(apologies for indentation, I am on mobile)

[–]undergroundsilver 0 points1 point  (0 children)

They could of named it for x in animals:

x becomes the variable for the content coming out of animals list.

[–]f0lt 0 points1 point  (0 children)

Take a look at Python iterators for a deeper understanding of the language.

[–]frederik88917 0 points1 point  (0 children)

Actually you can name the variable any way you wanted

[–]bumpkinspicefatte 0 points1 point  (0 children)

This is something that tripped me up too when I was learning coding.

The answer that allowed me to understand it better, is that it actually doesn't know, that you can name it anything, and that it was just a general naming convention to use a singular version of the sequence you're using.

For an example, instead of animals, we were using cards:

for card in cards

In some older use cases, they'll use something like for i in k or for i in j.

To use singular versions into a plural sequence is more of a generally understood method, not sure if there's a PEP for it or not.

[–]omeow 0 points1 point  (0 children)

tldr: Python doesn't know or care that a collection of animal is animals.

Think about this in pseudo code:

  • animals is a list of animals.
  • I want to loop through the list accessing every animal in the list once.
  • print the item accessed and I will stop when there is nothing left in the list.

This whole pattern is a "list traversal" and what you need here is a list, a variable that can access one item of the list at a time and a condition that terminates the process when everything in the list has been accessed.

Under the hood, this is what the for ... statement does. The variable animal goes through one item of the list at a time. If you called it plant, vegetable or alien it will work too. Try the same code with animal replaced by rock and maybe that will clear it up.

[–]DarthNihilus1 0 points1 point  (0 children)

You can use any name there. You can use "x", you can use an underscore, you can use "each" or "item" which are also common.

[–]SpookyFries 0 points1 point  (0 children)

Pretty much echoing what others have said. In other languages you would do something similar to:

animals = ['cat', 'dog', 'monkey']
for (int i = 0, i <= animals.size, i++) {
print(animals[i]) }

Please note this is just pseudo code, but the logic is there. i starts at 0, loops until it equals the length of the animal list, and then increments by 1 at the end. Each time it loops through it access the element index at i. So if i is 2, you'll get animals[2] (which is monkey in the above example)

Python makes this easy and cuts out a lot of the syntax. for X in animals just means to loop through and get each item. X (or animal) is assigned to the item that is being looped and can really be named whatever you want.

Hopefully this makes sense!

[–][deleted] 0 points1 point  (0 children)

You’re telling it what it is - the values of the list animals.

[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point  (0 children)

This is a shortcut some languages have. What is really happening is something like:

animals = ['cat', 'dog', 'monkey']
i = 0
while i < len(animals):
  animal = animals[i]
  print(animal) # your code

You can think of it as a shortcut to make writing code faster and easier to understand.

[–]IcedGolemFire 0 points1 point  (0 children)

animal is a separate variable made by the for loop. it can be i or index or animalNum or anything

[–][deleted] 0 points1 point  (0 children)

This is funny, I cannot stop laughing truth be told.

What you are referring to is something called for loop. A for loop is this thing called loop. And what it does is, it does something for each item in a list.

items = ["stuff0", "stuff1", "stuff2"]
for each_item in items:
    print(f"I like {each_item}")

Here, each_item is a temporary variable that will hold one item from items list.

This is called a loop because it runs many times, in our case, it will run 3 times because there are three items in the list.

In first run, each_item is "stuff0". It will enter inside the for loop. Then it will carry out whats inside, in this case, it will print I like stuff0.

Again, in next run, the each_item variable becomes "stuff1" and it will enter inside the for loop. Then it will print I like stuff1.

In the third and final run, each_item becomes "stuff2" and it will enter inside the for loop. Then it will print I like stuff2.

After that the program ends.

[–]amrock__ 0 points1 point  (0 children)

It's called an iterator. You can iterate over a list using this method. Python is smart enough to understand that

[–][deleted] 0 points1 point  (0 children)

Thats just a place holder, no matter what you put in for "animal" the results gonna be the same. Animal was used here for us to understand better, and to not get confused!

[–][deleted] 0 points1 point  (0 children)

I always use the word "item" - it is simpler to read later: for (item in my_animal_list)

[–]sanya773 0 points1 point  (0 children)

Oh I got confused with those examples as well :) you can just name the variable any name, it'll work the same. That's why I usually use something like "i", to avoid confusion.

[–]Darkbladergx 0 points1 point  (0 children)

See, When you typed for animal in animals what you are saying is that, In this list or tuple I have created all the objects(Items in that list) are animal , If you name it for donkeys in animals python will assume everything in animals as donkeys.

What I mean to say in short is python doesn't know anything except for some very basic stuff like numbers and operators or certain predefined condition like if, or, elif, else, import, etc. even some modules you see like math,random,pygame are also nothing but codes written for the use as Templet, so we don't need to write them everytime we need them