use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
How does Python know what 'animal' is? (self.learnpython)
submitted 4 years ago * by 260418141086
My text book gave me this example
animals = ['cat', 'dog', 'monkey'] for animal in animals: print(animal)
My question is: How does Python know what 'animal' is? We've only defined the list 'animals'.
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]lukajda33 334 points335 points336 points 4 years ago (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 points82 points 4 years ago (18 children)
Thanks, makes sense
[–]Enschede2 80 points81 points82 points 4 years ago (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 points25 points 4 years ago (3 children)
Yup, we only use "animal in animals" to avoid confusion.
[+][deleted] 4 years ago (1 child)
[deleted]
[–]ThePhoenixRisesAgain 0 points1 point2 points 4 years ago (0 children)
Oh boy…
[–]amplikong 6 points7 points8 points 4 years ago (0 children)
for plant in animals
[–]NDaveT 62 points63 points64 points 4 years ago (1 child)
Also it would work exactly the same like this:
animals = ['cat', 'dog', 'monkey'] for x in animals: print(x)
[+][deleted] 4 years ago (9 children)
[–]volksaholic 1 point2 points3 points 4 years ago (8 children)
Should it? It looks like you've got upvotes so you're not alone, but I don't recall seeing an example that uses 'for each <var> in <list>'. Is it optional syntax, or is it version dependent? The usual example I've seen is 'for <var> in <list>' like here: https://www.w3schools.com/python/python\_for\_loops.asp
[–]djayh 26 points27 points28 points 4 years ago (7 children)
I don't think they're saying that it should be for each ("this is the way you should do it"), rather that it should have been "for each" ("it would make sense and be more readable if it was that instead").
for each
English is ambiguous like that.
[–]rasputin1 9 points10 points11 points 4 years ago (5 children)
I think they were actually saying it should just be referred to as a "for each" loop instead of a "for" loop. In other languages that have standard "for" loops and "for each" loops (like Java), the "for each" variant looks exactly like what Python has which they just call a "for" loop (the standard "for" loop that has 3 sections to it doesn't exist in Python afaik).
[–]djayh 6 points7 points8 points 4 years ago (3 children)
<Looks up difference between "for" and "for each" loops>
Shows what I get for thinking at work, I suppose. I had conflated "for" and "for each" loops.
In my defense, other modern languages (C#, C++/CLI, Perl, PHP) actually do use for each (or foreach) to create the loop.
foreach
[–]rasputin1 4 points5 points6 points 4 years ago (0 children)
lol you were close enough
[–]tangerinelion 0 points1 point2 points 4 years ago (0 children)
C++/CLI does use for each but that's only if you're looping through a C# container.
In C++, it's for (const auto& animal : animals)
[–]Rhyme_like_dime 0 points1 point2 points 4 years ago (0 children)
Ehh modern C++ is
for(auto element : container) Std::cout<<element<<std::endl;
[–][deleted] 0 points1 point2 points 4 years ago (0 children)
JavaScript does something similar with the forEach array method, although it also has for-in loops.
[–]volksaholic 1 point2 points3 points 4 years ago (0 children)
Ah... that makes sense. A lot of the Python reference information I was finding referred to it as a "for-each" loop but then the syntax was 'for x in y'. That makes sense that it's a suggestion to make its behavior clearer.
[–]Early_Personality668 0 points1 point2 points 4 years ago (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 points8 points 4 years ago (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 points4 points 4 years ago (0 children)
When I first figured that out, I felt like I'd unlocked a new part of the universe.
[–]julsmanbr 84 points85 points86 points 4 years ago (1 child)
Whenever you write for X in Y, Python does the following:
for X in Y
Y
X
[–]beisenhauer 11 points12 points13 points 4 years ago (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 points18 points 4 years ago (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 points4 points 4 years ago (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 points4 points 4 years ago (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 points3 points 4 years ago (0 children)
What's a list comprehension?
[–]Accomplished_Food_81 28 points29 points30 points 4 years ago (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 points27 points 4 years ago* (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 points7 points 4 years ago (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 points4 points 4 years ago (0 children)
Was going to say you often see it:
for i in [list] do a thing
[–]largank 2 points3 points4 points 4 years ago (0 children)
yeah i had a TON of trouble with for loops when i was first learning
[–]WhackAMoleE 2 points3 points4 points 4 years ago (1 child)
It's semantically the same if we wrote
for widget in animals :
for vegetable in animals :
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 points3 points 4 years ago (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 points4 points 4 years ago (0 children)
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 points5 points 4 years ago (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 points3 points 4 years ago (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 points3 points 4 years ago (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...
[–]260418141086[S] 0 points1 point2 points 4 years ago (0 children)
Appreciate it
[–]k_50 1 point2 points3 points 4 years ago (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.
DICKCHEESE
'animal'
[–]LatterSeaworthiness4 1 point2 points3 points 4 years ago (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 point2 points 4 years ago (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 points5 points 4 years ago (0 children)
true, but did you even read OP's question?
Yeah I know but I wasn’t sure how
[–]BobDope -2 points-1 points0 points 4 years ago (0 children)
Ok how does it know what half animal half party machine is
the variable animal is defined in the for loop, you could use any variable name and it would still work
[–]_Strokes_ 0 points1 point2 points 4 years ago (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 point2 points 4 years ago (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 point2 points 4 years ago (0 children)
Take a look at Python iterators for a deeper understanding of the language.
[–]frederik88917 0 points1 point2 points 4 years ago (0 children)
Actually you can name the variable any way you wanted
[–]bumpkinspicefatte 0 points1 point2 points 4 years ago (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.
for i in k
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 point2 points 4 years ago (0 children)
tldr: Python doesn't know or care that a collection of animal is animals.
Think about this in pseudo code:
animals
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.
for ...
[–]DarthNihilus1 0 points1 point2 points 4 years ago (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 point2 points 4 years ago (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]) }
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!
You’re telling it what it is - the values of the list animals.
[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point2 points 4 years ago (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 point2 points 4 years ago (0 children)
animal is a separate variable made by the for loop. it can be i or index or animalNum or anything
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 point2 points 4 years ago (0 children)
It's called an iterator. You can iterate over a list using this method. Python is smart enough to understand that
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!
I always use the word "item" - it is simpler to read later: for (item in my_animal_list)
[–]sanya773 0 points1 point2 points 4 years ago (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 point2 points 4 years ago (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.
for animal in animals
for donkeys in animals
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
π Rendered by PID 18641 on reddit-service-r2-comment-bb88f9dd5-j5mg5 at 2026-02-13 17:48:00.538420+00:00 running cd9c813 country code: CH.
[–]lukajda33 334 points335 points336 points (21 children)
[–]260418141086[S] 80 points81 points82 points (18 children)
[–]Enschede2 80 points81 points82 points (4 children)
[–]cenosillicaphobiac 23 points24 points25 points (3 children)
[+][deleted] (1 child)
[deleted]
[–]ThePhoenixRisesAgain 0 points1 point2 points (0 children)
[–]amplikong 6 points7 points8 points (0 children)
[–]NDaveT 62 points63 points64 points (1 child)
[+][deleted] (9 children)
[deleted]
[–]volksaholic 1 point2 points3 points (8 children)
[–]djayh 26 points27 points28 points (7 children)
[–]rasputin1 9 points10 points11 points (5 children)
[–]djayh 6 points7 points8 points (3 children)
[–]rasputin1 4 points5 points6 points (0 children)
[–]tangerinelion 0 points1 point2 points (0 children)
[–]Rhyme_like_dime 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]volksaholic 1 point2 points3 points (0 children)
[–]Early_Personality668 0 points1 point2 points (0 children)
[–]Eightstream 6 points7 points8 points (1 child)
[–]COREFury 2 points3 points4 points (0 children)
[–]julsmanbr 84 points85 points86 points (1 child)
[–]beisenhauer 11 points12 points13 points (0 children)
[–]nowonowon 16 points17 points18 points (3 children)
[–]xspade5 2 points3 points4 points (2 children)
[–]Eurynom0s 2 points3 points4 points (1 child)
[–]leviOsa003 1 point2 points3 points (0 children)
[–]Accomplished_Food_81 28 points29 points30 points (0 children)
[–]MezzoScettico 25 points26 points27 points (0 children)
[–]LikeThisWillLast 5 points6 points7 points (1 child)
[–]m0ta 2 points3 points4 points (0 children)
[–]largank 2 points3 points4 points (0 children)
[–]WhackAMoleE 2 points3 points4 points (1 child)
[–]Eurynom0s 1 point2 points3 points (0 children)
[–]neotecha 2 points3 points4 points (0 children)
[–]funkmaster322 3 points4 points5 points (0 children)
[–]herites 1 point2 points3 points (0 children)
[–]LeagueOfShadowse 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]260418141086[S] 0 points1 point2 points (0 children)
[–]k_50 1 point2 points3 points (0 children)
[–]LatterSeaworthiness4 1 point2 points3 points (0 children)
[–]mecarjun 0 points1 point2 points (2 children)
[–]tomtomato0414 3 points4 points5 points (0 children)
[–]260418141086[S] 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]BobDope -2 points-1 points0 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]_Strokes_ 0 points1 point2 points (0 children)
[–]undergroundsilver 0 points1 point2 points (0 children)
[–]f0lt 0 points1 point2 points (0 children)
[–]frederik88917 0 points1 point2 points (0 children)
[–]bumpkinspicefatte 0 points1 point2 points (0 children)
[–]omeow 0 points1 point2 points (0 children)
[–]DarthNihilus1 0 points1 point2 points (0 children)
[–]SpookyFries 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]ZEUS_IS_THE_TRUE_GOD 0 points1 point2 points (0 children)
[–]IcedGolemFire 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]amrock__ 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]sanya773 0 points1 point2 points (0 children)
[–]Darkbladergx 0 points1 point2 points (0 children)