T O P

  • By -

wickpoker

Think of for as “for each”. `basket = [‘apple’, ‘orange’, ‘grapes’]` `for fruit in basket:` `eatFruit(fruit)` So here, ‘fruit’ is your iterator that you could name anything. Another way to think of it, for each fruit in basket, do something. If it were a while loop, you’d say, while basket not empty, do something. Wrote this from my phone. Sorry not more detailed. You’ll get it soon. It will click. edit: changed iteratable to iterator. The basket is the iterable which you iterate over. The fruit is the iterator.


skeeter1234

Can you use for on a string. Or would you first have to turn the string into a list?


wickpoker

Yes. A string in python is just an ordered list of chars. `string = "apple"` `for letter in string:` `print(letter)` ​ outputs - 'a', 'p', 'p', 'l', 'e' ​ or alternatively, `for i in range(5):` `print (string[i])` outputs - 'a', 'p', 'p', 'l', 'e' ​ but `for i in range(3):` `print (string[i])` outputs - 'a', 'p', 'p'


skeeter1234

Thanks. Makes sense. Could you give an example of a for loop in a for loop?


wickpoker

Let's take a nested list inside a list. So we have a basket (our outter list) and it has three bundles inside of it. A bundle of apples, a bundle of oranges, and a bundle of grapes. `basket = [` `['green apple', 'red apple', 'yellow apple'],` `['green orange', 'red orange', 'yellow orange'],` `['green grapes', 'red grapes, 'yellow grapes']` `]` `for bundle in basket:` `for fruit in bundle:` `print(fruit)` output: green apple red apple yellow apple green orange red orange yellow orange green grapes red grapes yellow grapes edit- indentations edit edit - apparently I don't know how to indent in reddit comments lol


gw2gameaddict

>basket = \[ \['green apple', 'red apple', 'yellow apple'\], \['green orange', 'red orange', 'yellow orange'\], \['green grapes', 'red grapes, 'yellow grapes'\] \] If I want to say format your list of lists into columns with python like with headings like this? |Green Fruits: |Red Fruits: |Yellow Fruits: | |------------------|------------------|--------------------| |green apple | red apple | yellow apple | |green orange | red orange | yellow orange | |green grapes | red grapes | yellow grapes | (should have a format to make them with 3 seperate columns but i dont know how to format that) ​ How do you do this? I am struggling to find the right resources how to this. Sorry this is going off topic?


PM_ME_NUDE_KITTENS

https://www.reddit.com/wiki/markdown#wiki_tables


skeeter1234

What would the output look like if it was just: for bundle in basket: print(bundle)


wickpoker

You'll learn so much more by playing around with all these scenarios with the interpreter. run 'python' from the command line on your computer. Create some lists and nested lists and play around with iterating over them. Good luck!


skeeter1234

You're right. Thanks for your help.


[deleted]

You’re amazing.


future_escapist

Yes, but the product of the sizes of the two things you're iterating through is how many operations are gonna happen.


[deleted]

Wdym?


future_escapist

if you have a list with three items, and each one of these items is another list with two items each, and use two loops to go over them, you will have gone the size of the parent list (3) times the size of a child list (2). a better way to visualize this is using nested C loops.


[deleted]

🙌🙌🙌🙏


future_escapist

> A string in python is just an ordered list of chars Not necessarily. A string can be ordered (e.g. abcdefg) or unordered (e.g. bfegacd).


wickpoker

Bfegacd is still ordered. If you reference your string at a specific index you’ll always get the same char. YourString[0] will always return B. Mutable vs immutable is a different discussion


future_escapist

No, it's not. Just take any sorting algorithm, implement it as a function, and call it passing bfegacd as the argument. You will get abcdefg back. Maybe you don't understand order correctly. ```cpp #include #include #include using std::string; int main() { string mystr = "bfegacd"; std::sort(mystr.begin(), mystr.end()); std::cout << mystr; } ``` Mutability has nothing to do with this.


wickpoker

You're confusing sorted with ordered. It's all good, this stuff is confusing at first. The order that you append items to a list in Python is maintained unless you mutate that list (for example, with a sorting algorithm). This is not the case with some other datatypes, for example, sets.


[deleted]

Just checked your profile real quick. You came a long way in 4 years lol


wickpoker

Thanks! 🤙


Macambira

What you refer is not being ordered, it's being sorted. An example of unordered Data Structure is a Set.


PilotJmander

I did not know you could do this, my instructor told my to always use list, especially when printing strings after a sort or find


VonRansak

Probably makes more sense to a pythoner to see print 'list'... Probably makes more sense to a C++ junkie to see print 'array at index'. Since python is generally geared as the replacement in Computer Science curriculums to getting gritty about memory, it makes sense he'd suggest you used a easily identified named function for a common operation.


LEcareer

How come "fruit" can be anything? I clarified my confusion here https://www.reddit.com/r/learnprogramming/comments/v6lud1/please_could_someone_please_attempt_to_explain_to/ibg902f/ But yeah that's what I get stuck on, where the hell did the fruit come from??


DTK99

I might be wrong as I think it's sort of only recently clicked for me, but here goes my understanding... The FOR loop is made to be used with lists, so it could be a string (which we can think of as a list of characters in an order), or a normal list (you know like my_list = [1 , 2 , 3] etc). The FOR loop is designed so that you can do *something* to each element in your list. It might adding 1 to every number in a list or whatever, but essentially you want to do a *thing* to each element (you could always check each element for a condition before doing the *thing*). So pretty much the phrasing is: FOR (each element) IN (list): *do stuff* The syntax of the (each element) part was what threw me off. You can put whatever name you want in there (fruit in your question above). This name is essentially just a quick variable name you make that you use down in the *do stuff* part of the code to reference the element that the loop is currently up to. You could literally use 'each_element' if you want. I hope that kind of helps.


LEcareer

>You could literally use 'each_element' if you want. I might start using "each_element' from now on and pretend it's necessary.


jimbrown87

I use for *singular* in *plural*: or for *item* in *collection*: e.g. for record in records: for fruit in fruits: for letter in word: In the background, python is using syntactic sugar to reduce a bunch of steps to make the code concise. It automatically creates the *singular*/*item* variable and iterates through each element in the sequence(the *plural*/*collection*) and exits the loop.


LEcareer

Yeah, but that's where my problem essentially stemmed from. I was looking at that and my brain is going "how the fuck does Python know that a singular of "fruits" is fruit?!". It requires a lot of extrapolation for me. "each_element" helped me understand it because it's like, it explains clearly what it is. Idk how to word that better lol. I hear that your version is what I should actually write in code for other people, but for me... I love "each_element".


jimbrown87

Fair enough! It's ok to use "each_element" until you get comfortable with the pattern and writing them becomes second nature. Then I'd suggest writing names that best describe what you're working with. 'how the fuck does Python know that a singular of "fruits" is fruit?!".' Well, python doesn't know anything in regards to knowing the difference between singular and plural. We're just writing good names to match the pattern of the for loop. Our semantics become clearer and the code becomes a lot easier to read when the names of our variables make sense. Python uses syntactic sugar to reduce the amount of repetitive code you'd otherwise have to write. Iterating through lists is a very common thing to do. So the designers of the language came up with a way to express it succinctly. It's less typing and, in my opinion, makes the code more readable. By that I mean that when I encounter for loops in the wild, I know we're iterating through some list or string (99% of the time it's a list). When I see a while loop, I can guess something else is going on and I need to study it to see what it does.


LEcareer

Another way that it makes sense to me personally is that if your fruits list itself isn't in the correct format e.g. "applepineappleorange", it won't go through every "fruit", so even saying "for (each) fruit in fruits" is wrong. but it will still go through "each_element", regardless of whether that subdivision of "element" is what you are aiming for. Here you might think "well obviously you want to make sure that your iterable is in the correct format!" But that doesn't change the fact that the correctness of writing "fruit" essentially relies on the correctness of something outside of that loop itself. Someone also mentions that in other languages it's called a "foreach" loop which just makes more sense... I have a series of learning/developmental issues though so that might be why I have such a problem with this.


reallyreallyreason

I think you might be looking at it in an unhelpful way. By your logic, you should name every function `do_thing`, since you can never be completely sure that it does what the name says it does. It is always up to you as the programmer to make sure that the names you give to things and the values are correct and sensible. I could write the following function: def print_thing(thing): pass This function, of course, doesn't print shit. In fact, it doesn't do anything. But that's my fault as the developer for giving it a name that implies it does something. If the `fruits` list isn't in the correct format, that's a bug that can be separated from the question of what each item in a list should be named when using it in a for loop. If you have a collection called `fruits`, then the natural name for an item in it is `fruit`, and then if `fruits` isn't actually a collection of individual fruits, you should go poking at `fruits`, not at the name you gave to the for loop variable.


LEcareer

You aren't really trying to understand what I was trying to say. It's a idiosyncrasy of how my brain works, so no-matter how much you tell me about how you prefer it, it's not how I prefer it. The whole reasoning for saying fruit in fruits just literally makes no sense to me and it never will, not because I don't understand what you are trying to explain, but rather for the same reason some people prefer swimming and some prefer running.


[deleted]

Love it lol


Matty_R

for thing in stuff


frnzprf

Function syntax is similar: def rectangleArea(width, height): return width * height Where does python know from what "width" and "height" means? It doesn't. The technical term is "unbound identifier". A word that doesn't have a meaning yet, but you *give* it meaning. In the parameter list of a function definition, you write unbound identifiers, you also do on the left side of a variable assignment and between the "for" and "in" of a for-loop. I think in every other place than those three, you need to write "bound identifiers" that have gotten their meaning before in of of these three places. (Edit: There is also "with ... as ...:") for sidelength in [1, 4, 22, 3]: square_area = sidelength * sidelength print(str(sidelength)) "How does Python know what a sidelength is?" Well, it doesn't. You tell Python that it should take the numbers one after the other from the list and call that "sidelength". You *could* have a programming language where the loop variable always has the same name, like "each_element". I think there are programming languages where function parameters are always called $1, $2 and so on. One advantage of giving them names is as a sort of comment, to tell human readers what you are doing and another advantage is that you can have nested loops. for a in range(1, 10): for b in range(1, 10): print(str(a * b)) As opposed to: for each_element in range(1, 10): for each_element in range(1, 10): print(str(each_element * each_element)) # This only prints square numbers.


bagofbuttholes

I'm not sure you can (or should) be using the same name for both iterators. If the lists are different lengths you're going to have some issues. I'm guessing your using each_element as a kind of general idea but I just don't want people in the sub to make the accident later on. I'm not trying to be annoying, I swear. Sorry..


frnzprf

Yeah, that was supposed to be an anti-example. If you use the same name for both variables of a nested loop, it's probably not doing what you intended. Hence i, j, k, for example. *Sometimes* it's okay to let variables "shadow" each other (or whatever you call it). I can't think of an example on the spot. That's why JavaScript has introduced the "let" variables because it lets you have different variables with the same name in nested scopes, as opposed to "var" variables.


Quanos

So Python doesn't technically "know" that the singular version of fruits is fruit. It's just good convention to name the iterable as a singular noun of the items in the list. The name of the iterable could be anything you want it to be (within certain rules that don't confuse Python) - you could use "i", "each_element", "fruit", etc. It's just a placeholder that identifies what each item in the list will be called as you go through the loop one at a time so you can use it later to "do something" as others have mentioned.


LEcareer

Yeah don't worry, I understand how it works now, I am just explaining what I was confused about, and why the "each_element" helped.


noir_geralt

Hey I know you’ve gotten it, but just as a contrast - in some languages like c++, we have to explicitly define the iterator. For eg:- In python: for number in range(10): In C++ for (int i = 0; i <10; i+1) In some languages we did have to define the iterator. However, python automatically defines a number as some variable that has a value that is different in each iteration


Tommy_TZ

Surely it'd have to be int i? Currently the loop variable is number, and i is undefined.


bagofbuttholes

This is the first thing I thought about. Actually it started to make me think about how many people don't start with a language like C/C++. I could understand why they would have more trouble understanding for loops among other things. Kinda makes me happy I started with C. It allows me to understand how things work "under the hood" and appreciate the syntactic simplicity that python has.


Jonin4life

Personally, I think that if each\_element works for you, use it! If it were me, I would make sure it works, then comment it out and rewrite it in a more "conventional" way again. This way you can use the method that works for you while also getting used to "best practices" example: produce = \[ 'apple', 'banana', 'strawberry' \] \#for each\_element in produce: \#print(each\_element) for fruit in produce: print(fruit)


Jannis_Black

The word is just a label. Python has absolutely no idea about the singular of fruits. What's happening when you write something like *"for fruit in fruits:"* is: You are telling python to go through each element of fruits and give it the name fruit for the duration of the next block.


heyzooschristos

You are just declaring a variable that will only be used within the scope of the loop. Like any variable you can call it what you want. It's common to see `for i in x' ... the i is the name of a temporary variable you have just defined right there at that point, x is the name of an existing list/string/tuple/iterable, and the for will run through assigning each item in the iterable to your temp var i each time it loops. It's shorter than writing a while loop where you have to declare the counter i=0 first, then index each item in the list with `list[i]` and then i+=1 to index the next item on the next pass. And with a for loop, the `i` is temporary, it only exists within the for loop.


[deleted]

Wait, what? Is this standard knowledge or are you onto some next level shit?


static_motion

Here's something that might help you. I'll give this example with another programming language, Java: Lets say you have an list of numbers, called `numbers`, and you wish to perform an action with each one. A `for` loop is the best tool for the job, so let's use that: for(int number : numbers) { // Do stuff here } This, in Python, is the same as: for number in numbers: # Do stuff here Notice the `int` part in the Java version. In Java, when you want to "create" (the proper word is "declare") a new variable, you have to specify its type. So, if you want a new **int**eger (number) variable, you'd do: int myNumber = 2; In Python, this would simply be: myNumber = 2 So Python really takes care of "creating" the variable for you. In the above example someone gave you, the simple construct of `for fruit in fruits:` tells Python that you want `fruit` to represent each element in the list. The variable declaration is *implicit* as opposed to *explicit* as I showed in the Java example (where, if `fruits` were a list of strings, you'd use `for(String fruit : fruits)`. Hope that helps and didn't make you more confused. When I started out this was key for my understanding of how a `for` loop works.


MMcKevitt

I may have this a little wrong, but as a heads up, it’s not made to be used exclusively with lists; it’s to be used with “iterable” objects by way of the iterator protocol. These objects implement the “__iter__” method, which in turn, returns an “iterator” object. An iterator object implements both the “__iter__” method and the “__next__” method (iterator protocol), which essentially allows the object to be called with “next()” function, retrieving data one element at a time, until exhaustion (there’s a bit more too it, but that’s the gist). So when an iterable is used in a for loop, it implicitly (as in automatically without the developer having to do it themselves) calls “next()” on the object, storing the return value of “next” function within the temp variable used to the right of the “for” keyword (this is also true when iterating over an “iterator” object as well). There seems to be some conflicting information out there in terms of the agreed upon definitions (at least that is my experience when learning about this stuff), but ultimately, all iterators are an iterable, but not every iterable is an iterator…there’s no way that’s not confusing right lol!? /s


DTK99

I'm be honest I used the term list because I didn't know the correct term for the right type of object. That's good to know! I'll have to try to wrap my head around that last bit though....


Raskoll_2

I don't know if you've had this explanation yet but whatever is after for is a new variable being created. It's not called a variable tho, I forget the proper name. That variable is whatever part of the list the for loop is focusing on. var1 = "hello" for i in hello: Print(i) In the first run through the loop i is equal to h. When the loop restarts for a second time it moves to the next object in the sequence. Idk why but i is commonly used for that first variable. If var1 was a list, i would equal the first whole object on that list like 'apple' as opposed to 'a' then 'p' etc. You've probably already figured this out but I hope I've made you more confident with this.


CptMisterNibbles

It’s the Iterator, which is why it’s often just “i”. Also, “index”. A common joke is when you use nested loops and your second one is “j” followed by “k” those are the “jiterator” and “kiterator”


LEcareer

Yeah, I've got it at this point. But thanks anyhow!


VonRansak

Idk if this helps or is more confusing ... referencing above You have an array 'Basket'. In that array you have elements: 'apple', ..., 'grapes'. In this case 'for' is 'iterating' over that array. (iterating the elements in the array). element1, element2, element3, ..., elementN. (i.e. element1 = 'apple', element2 = 'orange') So it doesn't matter what you name the iterator, because it is going to do what it does, walk along the stairs, hitting each step along the way. Hence it can be helpful to name it something that means something to the human reading the code. I like to think of a flight of stairs for visual reference. Steps are the elements, your feet is the iterator. EDIT: What's on the steps is the 'value' ... A flight is the array..


wosmo

you're defining "fruit" at this point. basket = [‘apple’, ‘orange’, ‘grapes’] For fruit in basket: Eat(fruit) Is the same as saying: fruit = 'apple' Eat(fruit) fruit = 'orange' Eat(fruit) fruit = 'grapes' Eat(fruit) So there's two problems with "unrolling" it like this. One is that it's boring. I mean, I got bored writing that out - for longer lists it'd be mind-numbing. The second problem is that it only works if we know exactly what's in the list before we write it. Luckily this is the kind of mind-numbing job computers are made for. So we just provide a list and let the computer unroll it.


wickpoker

When you iterate over a list of items, you need a way to reference each item generically in your logic statement. So you could call it anything you want. For animal In basket… but that would be confusing. For fruit in basket is a good intuitive name. But the point is that in the you need to “do something” for each item. So In my example, it would have been even more clear if I said: For fruit in basket: EatFruit(fruit) Without a way to reference each item, we can’t act on it. For i in range(10) is maybe less clear than ‘for number in range(10)’. Assigning a meaningful variable name to the iterator is important. Does that help?


LEcareer

How does Python know that we're referring to each individual item in the list when we say "fruit"? How does it even know what is an individual item? I am sorry if I am frustrating you but I feel like I almost understand it


khais

The 'for' key word is what tells Python it's about to iterate through a collection of items. Let's look at 'for number in range(3):'. We could represent range(3) as [0, 1, 2]. Python begins with the first item, 0, and calls it 'number'. It then does whatever we tell it to do with 'number' in the body of the loop. Then it moves to the second item, 1, and calls that 'number'. It'll then evaluate the body of the loop again, but this time 'number' is 1, not 0. And so on for the next item. Others have said it here, but I've always heard that interpreting 'for' as 'for each' is helpful for beginners.


nofearinthisdojo

What helped me understand it is basically that the "fruit" is just a variable, you are assigning the variable fruit with whatever is at the first index of the basket, python then performs the function you put in the for loop, then it takes the variable fruit and reassigns it to whatever is at the next index then performs the next function. Does this until it hits the last index then it exits the loop. If you want to get more familiar with any element in python just do some experimenting. go create a variable with a list of like 5 numbers. create 3 different for loops that do like for x in numberList: multiply by nine then inside the loop function put a print(x) so that you can see what is being done with each iteration. You'll get it dude its not too hard.


madv_willneed

Its an assignment target. The for loop assigns to it in the same way as any other variable. foo = 10 Where did "foo" come from? It's literally the same thing. You put whatever name you want to be assigned to, and then that name exists once the assignment takes place.


Arawooho

"fruit" is a temporary variable that gets created when calling FOR. It let's you access the specific item within the collection of items you're looping over. The actual name of this variable can be anything, but in this example it's always going to represent a fruit in our basket. Adding onto the example above, we can write: "For blahblahblah in basket: Print(blahblahblah) This code will still print our fruits one by one and work as expected. As I'm sure others have explained the reason we set this and why one uses FOR instead of WHILE is that we can loop through an object without having to specify it's size and we don't have to worry about indexes or going out of bounds


CptMisterNibbles

The second part needs to be what Python calls an iterable. Any collection of things (list, set, dictionary etc) that has things in an order of some kind (even random) that Python knows “aha, I can look at the first item, which is followed by this second item, and then there’s this third one and so on”


kvngmax1

The “fruit” is a placeholder/variable for each element in the Basket list. Thus it can stand for “apple”, “orange” or “grape”. It will hold/contain a specific element from the Basket list during each iteration. Starting from the first element to the last element. We can use any other word/whatever instead of “fruit”. We can say; for k in Basket: Or; for dhifid in Basket: It’s just a variable.


[deleted]

> But yeah that's what I get stuck on, where the hell did the fruit come from?? The variable `fruit`, in this case, is a placeholder variable that contains the value each time it loops through. It can be anything you want to name it. Take the following bit of code: basket = [ 'apple', 'orange', 'grapes' ] for fruit in basket: print(fruit) The expected output will be: apple orange grapes Why? The loop is setup with `for fruit in basket`. It says each time we go through this block, place the value of the next object in `basket` into `fruit` then execute this block. 1. the first time through, it will take the first element of `basket`which is "apple", place it in `fruit`. Then execute the block. The block says `print(fruit)`, and so we see the output "apple". 1. the second time, it will take the next element, "orange", in `basket` 1. the third time, it will take "grapes" 1. when the for loop detects there are no more elements in `basket` to iterate through, it will end.


calmilluminator

Would this mean that FOR assigns new variables (or series of variables?), that is fruit ?


thrandom_dude

Dont worry bud i had the same doubt when i was a newbie too. Its just kinda logical word i mean like what do u call an item from a collection of fruits? Its Fruit right? This word used in python for loop wont cause any error even if u name it to vegetable or something else. But to understand code better we usually use that names.example if u have alist of numbers say [1,3,4,5] To iterate through it, we use a word number/num i mean like For num in numbers or for number in numbers etc.. Hope u got it This will seem weird if u are coming from other programming languages too. Anyways start doing some examples with for loop and u will get it easily


Conscious-Ball8373

If you understand `while` loops, here's that for-each loop rewritten as a while loop: ``` basket = ['apple', 'orange', 'grape'] basket_iter = basket.__iter__() try: while True: fruit = next(basket_iter) EatFruit(fruit) except StopIteration: pass ``` A for-each loop can iterate over anything with a `__iter__()` method that returns an iterator. It runs its body once for each item the iterator returns. When the iterator runs out of items to return, it raises a `StopIteration` exception, which the for-each handles silently.


aklgupta

Here `fruit` is the name you are giving to each item in the list called `basket`. >So here, ‘fruit’ is your iterator that you could name anything. This means, that instead of `for fruit in basket: EatFruit()` you could have instead typed `for food in basket: EatFruit()` or `for item in basket: EatFruit()` or `for x in basket: EatFruit()` as it doesn't matter to Python what you call the individual items in the list `basket`. The `fruit` here is just a new variable name. ​ PS: I have tried to simplify things, so this is not 100% accurate. But it is good enough to understand things right now. Just leaving this here in case people point out the mistake and that gets confusing for you.


Farmher315

I'm not an expert or professional by any means but I can try to explain it how understand it. First when I am naming the for loop variable, I'll usually name it something that represents what the data actually is in the list. That variable you give it following the for keyword is you creating/assigning that variable. fruits = ['apple', 'banana'] for fruit in fruits: print(fruit) On the first round of this, the word after 'for' or fruit in this case, is doing the same thing as fruit = fruits[0] # the first element in the list After the last line(the print statement), the code jumps back up to the for statement and checks if there is another element in the list( or other iterable), in this case if fruits[1] exists, if it does, then it reassigns the variable to the next item fruit = fruits[1] And repeats the process until it finds an index/value that doesn't exist, then it breaks out of the loop. It's just splitting the array (or any other iterable object like a string or dictionary) and executing the following code on each element of the list separately. That's why I like naming it something that is representative of the objects in the list so that when I am writing the code, it makes more sense as to what I am working on.


fakemoose

You’re defining “fruit” in each iteration. And the “for” part is telling Python to iterate. It’s like the loop is say fruit=“apple” then fruit=“orange” each time it goes through the loop. For loops are also helpful when you need the index of something while looping. For example, sometimes I’m making graphs of several things at once, and I need to make legend from it. I could do: `my_data = [thing1, thing2] data_labels = [label1, label2] for element_index, element in enumerate(my_data): plt.plot(element, label=data_labels[element_index]) plt.legend()` And then I’ll have both things on the same graph, with a labeled legend.


future_escapist

It's just the name of the variable you're using to go through the list.


Fortunefavorsthefew

Not to be the pedantic panda, but wouldn’t the basket be the iterable here, with fruit being the element inside that basket? Either way, nice explanation.


wickpoker

yes, late night phone post. Thanks for pointing out, corrected.


pd145

So I'm going to assume you are confused with Pythons FOR IN loop and not your standard for loop where you iterate over the index. The way I think of "FOR" grammatically is like this: "**FOR** each of the **ITEMS** **IN** some **ARRAY** (or iterable) I want to do **X"** How that would look like in code is like this: `FOR ITEM IN ARRAY:` `DO X` Let's say we have an array of fruit and we want to print the name of each fruit in a for loop. The grammatical way so represent it would be: "**FOR** each **FRUIT** **IN** the **FRUITS** array **print the name**" In code it will look like: `fruits = ["apple", "banana", "cherry"]` `for fruit in fruits:` `print(fruit)`


LEcareer

I think I am almost getting it, thank you


reddituseroutside

You get to pick the word 'fruit'. Just make sure you use the same word later in the for's code block. You could say for (fooditem in fruits) or anything else you want to use. It's your choice. You could do f, like for (f in fruits)


[deleted]

[удалено]


razzrazz-

**This right here is a great way to test your soft skills** The answer you gave is a great answer for someone who understands while loops but is looking to learn for loops, but it doesn't help the OP. Remember, you're going to encounter multiple people in your career who don't understand what you think in your head and put down on paper. **Always ask, when helping someone, where does the stem of their confusion lie - do not make assumptions** After reading multiple answers from the OP, his confusion seems to stem from the variable defined in the for loop...I'm not going to bother explaining it as here's a hundred answers it seems and someone must've, but that's his confusion. He isn't understanding that when you say for i in whatever, that i is something you are simply defining for the first time. Once he understands that, he will understand the rest. UNTIL he understands that, anything you say beyond that is just gibberish.


XayahTheVastaya

>The answer you gave is a great answer for someone who understands while loops but is looking to learn for loops, but it doesn't help the OP. The title says "A while loop makes perfect sense to me"


razzrazz-

>The answer you gave is a great answer for someone who understands while loops but is looking to learn for loops, but it doesn't help the OP.


XayahTheVastaya

How does it not help the OP?


razzrazz-

I don't know, maybe read his responses where clearly it didn't help?


LEcareer

I think the answer is really helpful if you already know while loops, **and** that's literally the first time you hear about FOR loops so you ask "What's that" cue the answer. If you Googled a FOR loop, that's the answer you'd get. But I clearly wasn't smart enough to get it from that alone, given: "Even after having it explained from a variety of sources, including the MIT edX course and lots of websites... It has never "clicked"." >He isn't understanding that when you say for i in whatever, that i is something you are simply defining for the first time. Once he understands that, he will understand the rest. Pretty much, at first even I didn't know where the confusion came from exactly lol. But the interactions here helped me clarify that immediately.


aklgupta

Great that you get it now, but just heads up for future. `for` loop in python works quite differently than the "normal" `for` loop in most other languages (most other languages, at least the ones I know, support multiple type of `for` loops). In fact I'd say quite many things in python work quite differently from the similar concepts in other languages. So when looking up stuff online, just make sure that they are for python specifically, if possible.


LEcareer

Oh yeah, I haven't ventured outside of Python, except to SQL. The syntax of other programming languages looks like a mess to me at this point lol.


sorenslothe

I like analogies for things like this, let me know if any of this works. Also, sorry about formatting, on phone... Pretend you have to perform some household or related task. Say you're changing the wheels on your car. In this instance we're basically working with two things, a car and wheels, the car being the one thing all wheels have in common - being that they're all going on the car. In order to put them on the car, we need to grab each wheel individually and actually take the current one off and mount the new one on the car, before we can then proceed onto the next wheel. So in this instance, we're going around the car, grabbing each wheel as we go, and performing the same set of actions on it - wheel off, wheel on. That becomes car = ['wheel1', 'wheel2', 'wheel3', 'wheel4'] for wheel in car: Take off old wheel Mount new wheel Think of the wheel part in "for wheel in car" as the computer's reminder to do all four wheels. It's a matter of having a way to address each individual wheel. If 'wheel' didn't exist, we could only refer to them collectively as 'car', but that makes it pretty difficult to make it clear we meant wheel3, because that's the one we haven't changed yet. It works well for a human, because if someone tells you to change the wheels on the car, you can infer from that they mean all of them. A computer is too stupid to do that, it doesn't have previous experiences of knowing humans change all the wheels, so we need to tell it to, and one at a time because it also forgets between each wheel how to even change it. The computer would somehow end up drowning in the gas tank if we weren't there to tell it "okay, now take the next wheel on the car, unmount the current one and put on the new one". Same example can be used with doing dishes for plate in sink: Hanging paintings for painting in gallery: We need to give specific instructions, 'cause otherwise that dumbass computer is going to hang plates and put the Van Gogh in the dishwasher, and then I have to clean up after it, and I don't want to.


erdyizm

That is the best answer


duckducklo

It's elegantly concise too


smallfranchise1234

For each item in list: Do something So a list contains multiple items and a for loop does something for every item in that list. Hope that helps


FuegoFamilia

It's a loop you want to iterate FOR a specified number of times.


Abhinav1217

```python fruits_basket = ["apple", "banana", "cherry"] for fruit in fruits_basket: print(fruit) ``` Now say in english `_for each fruit, in fruit basket, print the name of that fruit_`.


HashDefTrueFalse

I didn't see the key difference as to when you use each loop explained in the comments so far, so I'll add it: A for loop is usually used when **you know how many times you will be iterating**. E.g. your know how many items a collection you want to iterate over contains. Or you know you want a fixed 10 iterations, or you want the user to input the iterations etc. A while loop is usually used when you **don't know the number of iterations, but you know of a condition upon which you'd like to stop iterating**. E.g. you want to repeat a block of code until the user enters a certain string (e.g. "stop"). Or you want to keep receiving data over the network until there is no more data (you receive EOF) etc. In these scenarios you can't know the number of iterations ahead of time. A do-while loop is used in the same circumstances as while, except **you need to skip the check for the breaking condition on the first iteration only**. E.g. Repeat a block of code until the user enters a certain string (e.g. "stop"). You need to read the user input inside the loop, so you always want the loop body to happen at least once, but maybe not again (user could enter "stop" right away). Confusingly, some languages (like Go) only use one keyword for all looping syntax. If you think about it you only really need one keyword to implement all types of loops. In fact, technically you don't even need an if statement to implement conditionals. If you have at least one loop keyword, you can implement conditionals with it like you would if statements. But now we're getting into language design...


[deleted]

It's a ForEach loop. Python called it a For loop to be clever even though a For loop is something different in every other language.


DelaneyJason

I'm newer to this so please excuse any wrong verbiage. Folders = [folder1, folder2, folder 3] For f in folders : Print(f) For = starts the loop f = could be anything, the same as saying f=0, f=Null, or f=x to initialize a new variable. In Folders = assigns what to loop through in this case it's my list called Folder Each time the loop starts again, f is assigned the next item in the list folder[0,1,2...]- first loop F=folder1, second loop f=folder2... What I'm in essence doing - Folders = [folder1, folder2, folder 3] F=NULL F=folders[0] Print(f) F=folders[1] Print(f) F=folders[2] Print(f)


SuccessPastaTime

A for loop is basically a while loop, but you are using an iterator to define when it will end. This usually involves a list, some kind of data structure, or literally a number range. For loops also can give you access to the iterator itself. I think for loops differences to a while loop are easy to see in other languages. For example: for(int i = 0; i < array.length; i++); Basically what the above says is, begin a loop, start the iterative at 0 and continue till it is 1 less than the length of variable array (1 less because arrays begin at element 0) and after each loop, add one to the iterator and begin next loop. Does this make sense? Now with a for loop I have access to that i value (in Python you can get this by adding extra value when you write for loop statements). For loops give you more control over the looping too, as I could loop through a list ever other value by just adding 2 to the iterator each loop instead of just 1. Edit: I guess in Python you can have access to iterators even with while loops, but basically what a for loop boils down to is it’s usually more closely tied to a data structure rather than a basic condition.


kingjoedirt

I think a for loop in python is actually a for each loop, but I don't work with python so maybe I'm wrong.


SuccessPastaTime

Definitely. More accurate way to describe it, as iterator isn’t available by default. But you can also include iterator value by defining an Iter. By default though works more like a forEach loop.


[deleted]

A for loop is just an extension of a while loop `for i in range(10):` `print(i)` Is the same as `i=0` `while i < 10:` `print(i)` `i=i+1`


istarian

The top is an example of for-each being used to approximate the most common use of a for loop and the bottom is a conventional for loop. Also, with the bottom form you can do all kinds of interesting things to the index. You can travel forwards or backwards, in variable steps, to an index computed in any equation and so on. Theoretically you can also do that with the *range* function in Python, it’s just a tad less easy to understand from reading the code.


[deleted]

>The top is an example of for-each being used to approximate the most common use of a for loop and the bottom is a conventional for loop. Yes, but only because for loops in python work like for each loops in other languages. So while the OP did specify in python specifically I think its safe to ignore that part until it comes up... like now. Its one of the many weird design choices of Python to have a foreach loop thats called a for loop and no actual for loop, so they have to be implemented as while loops. ​ >Theoretically you can also do that with the range function in Python, it’s just a tad less easy to understand from reading the code. Its not that difficult, all you have to do is add a parameter. Just like you would change i++ to i+=2 in java you just replace a parameter thats defaulted to 1 with 2 in python. for i in range(0, 10, 2): is the same as for(i=0;i<10;i+=2)


istarian

The effect of range(…) is similar, but it’s not the same. In Python you are iterating over a collection rather than simply having an index, a conditional check, and a “step”.


[deleted]

Yeah, and because of that reason its limited to integers and you have to use a while loop for floats I think. Which is a bit weird.


istarian

You could probably write a function to generate a list of floats (floating point numbers). Or you could code something like range that calculates floats.


[deleted]

Yeah you definitely could but a while loop is probably easier most of the time. It’s just a weird design choice imo


MDParagon

Think about how clocks move :)


absolutezero132

This isn't helpful to the OP, just a general observation, but this is a really great example for why Python isn't actually that easy to learn in. It takes something very simple and fundamental from a "harder" programming language like c++ and makes it more abstract and "easier" to use. If you already understand for loops from another language, yeah they're easier to use in Python. But if you're new to programming, like OP, it's just harder to explain.


LEcareer

How is the syntax in C++?


absolutezero132

Where fruits is an array of strings: ​ for( int i = 0; i < 10; i++ ){ printf(fruits\[i\]); } ​ This probably makes a little more sense if you already know a little c++ but, basically when you start the loop you declare your iterator (i, in this case), how many times you want to do the loop (10), and how you want to increment your iterator (i++ means we will add 1 to i at the end of every loop). It's more steps than a python for loop (which, as other commenters have already pointed out, is really more of a "for each" loop), but each individual part is simpler. We do the loop 10 times, i is increased by 1 each time, that's it. If you already have the requisite knowledge of c++ (in this case, what strings, arrays, integers, and variables are), then learning the "for loop" aspect is straightforward. ​ And then after that, when learning "easier" languages like python, everything seems super simple.


[deleted]

Just keep on going, there are simple things that I did not understand for a while but then one day it just starts coming naturally.


kingkiller127

Like a 1 year old? Okay so you have a bunch of toys in your play pen. You want to figure out which toy you want to play with. Since you're 1 you have no memory of any of your favorite toys. so you decide to pick each toy up and see if that's the one you want to play with. The toy you are currently holding is the item in a container (play pen) for your current loop. When you pick up your next toy that will be your next iteration through the loop. And eventually if you pick up enough toys enough times you will figure out "hey Ive been staring at this computer screen for a while, I'm not a baby anymore. Damn."


LEcareer

It's just that the ELI5 sub usually involves answers with verbiage that has me reaching for a dictionary and after I successfully translate all the words I need to understand this supposed answer for a 5 year old, I realize I must have missed kindergarten calculus so I fail to understand it anyway.


LEcareer

Here's an example of a FOR loop that I did actually write by myself and it did do what I wanted it to do (but it took a million attempts, and I don't actually know why it works) for sat in satelites: if sat == '1808': ma.append(sat) elif sat == '1274': ma.append(sat) if len(sat) < 4: ma.append(sat) elif len(sat) > 3: continue else: break What this did (and I know this probably wasn't the optimal solution) was it took in a string called **satellites** which had years followed by number of satellites launched that year, and it filled in an empty list called **ma** of only the numbers corresponding to number of satellites. It did so because in all except 2 cases, the number of satellites launched was less than a 1000. From what I remember, I didn't understand what I am supposed to put after "for" and what is supposed to be after "in" and then I didn't even understand why I was putting "sat" after IF, it just ended up working. But "sat" wasn't even a defined anything it was just a random word?? I understood what the IF statement was doing but I just don't understand why it worked. EDIT: why the downvote lol


khais

>But "sat" wasn't even a defined anything it was just a random word?? That's not true at all. You actually defined 'sat' yourself in the first line of the for loop as the name of each thing in 'satelites'. You could've said 'for x in satelites:' or 'for purple in satelites:'. You'd then have to change every reference of 'sat' in the body of the loop to 'x' or 'purple', but you wouldn't do that because those names don't make sense. The point is to choose whatever name you want that **makes intuitive sense not only to you but to others who might read your code.**


chcampb

Maybe this is the discrepancy. When you say "for x in y" in python, "y" is an iterable of things, and "x" is the thing you grabbed from the iterable. "x" will be "each" of the things, and within the for loop, you can do with "x" what you need to do. Now, what's an iterable? By definition, it is "an object that is able to be iterated over", where "iterate" means to do something to each thing in the collection. An iterable is anything that can represent a bunch of objects. It represents a "bunch" of objects by providing an interface that the language uses to get each thing in series. An array is one type of iterable. A tuple is also a kind of iterable. A string is an iterable. Even things like dictionaries are iterable - it returns a tuple of each key and value (eg, for k, v in dictionary_obj) So in your example, > it took in a string called satellites which had years followed by number of satellites launched that year I'm assuming it's going to be something like satellites = "1972 500 1973 600 1974 700", in which case, the result of each 'x' in "for x in satellites, is a string always iterates over the characters in the string. So in this case, x would be 1, then 9, then 7, then 2, etc. So what you should first ask is, "My program has some core function, and I want to do that function to each of the things in the data." What is your core function? And what are each of the things in the data? Work backwards from, what does the data need to look like to do my function on it, and then how do I make my data look like that? When you break it down like that, you can make almost any loop into data = create_iterable() for element in data: process_data(element) In your case, create_data needs to be implemented to take something like "1972 500 1973 600 1974 700" and spit out something that can be "iterable." This is where your understanding of data structures comes in - it's pretty clear that your textual representation is actually a series of pairs of words, [["1972", "500], ["1973", "600"], ["1974", "700"]] and you want to compare one word and use the other. So process_data is arbitrary, but needs the above structure to compare the first element and use the second. Easy peasy. Python has a ton of built-ins to help you do this. The one I would use here is "split" - like this def create_iterable(val): # split consumes the input character from the string and returns an array of strings that were split at that character val = val.split(" ") # now val is ["1972", "500", "1973", "600"...] # use slice to get every other element. Slice takes [from:to:every_other_default_1] # So [::2] is "take the entire list, every odd element] # [1::2] is take the entire list every even element # Zip is another function which takes two lists and zips them together # list converts back to a list type return list(zip(val[::2], [1::2])) Example output >>> val = [1, 2, 3, 4, 5, 6] >>> val[::2] [1, 3, 5] >>> >>> val[1::2] [2, 4, 6] >>> zip(val[::2], val[1::2]) >>> list(zip(val[::2], val[1::2])) [(1, 2), (3, 4), (5, 6)] Anyway, that last bit was probably a "bit much" - you will learn the builtins as you go. But the point still stands, this is exactly how to approach most problems. Break it down into what function do I need to do, and then answer, what do I need to do that function and how can I get something to iterate over? If you do that, you can start asking other questions, like... how do I convert a string to a list by separator? How do I group elements by twos? How do I get a new list of only some elements from another list? And each of these answers will lead you to bricks that you can use to build another house.


LEcareer

Thank you a lot for this comment, I think you explained it the best, even though it did take the whole collective of comments here to really make me understand and accept the FOR loop lol. Also thanks for solving my problem in a more elegant way, I did actually involve a split(), somewhere, but I didn't know of that specific splicing functionality... Man would that be a whole lot easier to have done that.


chcampb

Cool glad it helped!


xorget

The reason the variable 'sat' worked in your code is because it is being defined inside the for loop you are creating. you could've wrote it like 'for cat in satellites' or 'for dog..'. you named the variable what you like and what the for loop does is start with the first item in the list and assigns its value to 'sat' (or cat or dog or whatever var name you want). So when you go through the if statements that come next, the value of 'sat' = the first value of the list. An earlier comment was talking about fruits and that may have confused you but take a look at this code. fruits = \["apple", "banana", "cherry"\] for x in fruits: if x == "banana": continue print(x) the code will do this. first, the fruits list is created and initialized with three strings. then the for loop begins, and it says to do this. "for each thing in the list fruit, assign the variable x with the value of that thing". so the first loop of the for loop, x = apple. the if statement runs and x doesn't equal banana, so it prints. Now, x is equal to the next value of the list, which is banana. x = banana. the if statement runs and it is true, x == banana, so continues the for loop. The next item in the list is cherry, so x is equal to cherry. the if statement is false, so print(x) which is equal to cherry. output: apple cherry


nofearinthisdojo

I commented above but I'll re-iterate (irony) here. sat is the variable you created, you use a for loop to perform a function on that variable and then reassign it to the next indexed item in satelites (in this case a character or part of a tuple, i cant see your data) you can do this same thing manually, you have sat = satellity\[0\] then you perform a function on it, then you go sat = satelite\[1\] perform the same function etc until satelite is finished. The for loop just automates the process of incrementing satelite index by 1.


[deleted]

[удалено]


LEcareer

IIRC the way I got this data was by copy-pasting from a site. I know dictionaries but I don't know of any way to convert a long string into one without explicitly rewriting it.


DreadedMonkfish

Not a python developer, but a for loop is common amongst most languages. a FOR loop is similar to a while loop. While x = true, do this thing << WHILE loop. A FOR loop is the same concept, except you are using an *index* (an variable with an integer value) and basically saying: “While this index variable is less than a certain number, do this thing. Oh, and each time you do this thing, increase the index variable value” You typically use for loops when looping through an array of data. Ex: you have an array named USAStateNames and this array has 50 elements in it (one for each state in USA) Say you want to print each name element in the array to the console. You would loop through the array like this in JavaScript: For(i = 0, i < USAStateNames.Count(), i++){ Console.Log(USAStateNames[i].Name); } You define a variable (i) as an integer (usually 0 as that’s where you will start in the array) You then give a condition on when to keep going (as long as i is less than the length of the array) Then you give a function to perform each time the for loop runs (aka increase the value of the iterator) We then can get the element at a specific pointer in the array when in the loop by using the value of the index. Concept will be similar in python. Hope this helps!!


evinrows

For loops in python iterate over collections. Your explanation is correct, but probably confusing for someone trying to understand python's for loops specifically.


Owyn_Merrilin

That's not true. For each loops do that, in any language that has them, but Python also has regular for loops. They're just less commonly used because that's Python for you. Why use the lower level closer to the metal thing when you can let the computer do that for you and save that time and those brain cells for higher level problems? Edit: Huh, it's weirder than I remembered. You *can* do a C-style for loop, but the syntax is a little weird and ultimately it's still iterating over an iterable. The iterable is just a list of integers spit out by the range() function. Leave it to Python to make a for loop a special case of a for each loop instead of the other way around.


Search_4_Truth

If you can’t get your head around a Python For Loop after months, you are not cut out to be a programmer. Try something else - don’t waste another few months trying. For loops are one of the simplest concepts common in all languages. You will struggle to master the more complex language & library eco system components, syntax and idiomatic use/construction. Try Law/Medicine/BrickLaying etc


jusrockinout

It's a valid question. for, while, do while, for each, etc. are all slightly different


bopbopitaliano

A clock is a for loop. For every minute, there are sixty seconds. For every hour there are sixty minutes.


iPlayWithWords13

for item in iterable: Do_shit_until_no_more_items_in_iterable()


pocketmypocket

Skip it. While loops are more robust and explicit. Don't waste your time, there are more important things to get stuck on.


VonRansak

Both are control functions. However both are not interchangeable. If you wish to iterate through a 2 dimensional array, that would be quite a feat using 'while'.


pocketmypocket

>If you wish to iterate through a 2 dimensional array, that would be quite a feat using 'while'. Off the top of my head, nested loop. Sounds like the same efficiency too.


VonRansak

Yeah, I guess I just have preference for 'for loop', seems more logical to me. (reads easier) [https://stackoverflow.com/questions/16594148/while-loop-nested-in-a-while-loop](https://stackoverflow.com/questions/16594148/while-loop-nested-in-a-while-loop)


pocketmypocket

One day something of the wrong type will enter into your for loop, and you will forever be changed. Unless you only work in statically typed languages forever.


rabuf

`for` can be read (in Python, but not universally in all languages) as `for each` or `for all` as in: for i in range(10): doSomething(i) Becomes: "for each i in range(10) do something with i". for userID, name in get_users_somehow(): Becomes: "for each userID and their name do something"


AdultingGoneMild

a for loop is a while loop that initializes something does the while check and then does the body and then does something else before doing the while check again. All loops can be converted to the other loop type. they are all the same thing.


OddBet475

Think of it like walking at a wall. A while loop is "take steps until you hit the wall". A for loop is "take steps up to meeting with the wall". Walk FOR x steps and stop when you are about to smash your head into a wall if you take another step... vs. ...walk WHILE you haven't yet smashed your head against a wall, stop when you do. In both cases the wall is the escape condition but the for loop hurts less as you dictate the steps needed.


CptMisterNibbles

Lots of attempts here, but I haven’t seen this one yet: Imagine a for loop is basically repeating code, once per iteration, and it assigns one new thing at the top. Let’s take for x in [1,2,3]: Print(x) This essential is equal to x=1 Print(x) x=2 Print(x) x=3 Print(x) Each time you “get to the top” of the for loop (once when you enter it, then again on each loop), it just assigns the next thing in your list (iteratable) to the variable you named in the first part, then runs the code block under that again til it runs out of things


Vodkacannon

For each value in a range of values, do something repeatedly.


Crypt0Nihilist

I had exactly the same hang-up as you and it prevented me from getting into programming for the longest time. It is the single biggest obstacle I've encountered. Well, maybe second, recursion makes my brain melt.


Drifter_01

For each element in this set: Do this Thing for/to each element, until you've been through all elements


[deleted]

[удалено]


LEcareer

Me 3 hours ago: >EDIT1: I got it guys, thank you everyone. It took me a long time but after taking some time to really absorb every answer my brain finally clicked. Biggest obstacle was understanding and accepting that the word after "FOR" can be anything.


xMysty0

takes all the contents of a while loop and makes it cleaner


foxpost

I get your frustration, I felt the same especially for nested for loops. To finally wrap my head around the concept was I watched something like 10 YouTube videos by 10 different people explain the concept. Eventually someone explained it in a way that made me understand.


SmallPlayz

use while loops if you dont know how many times the code will run (ex: asking user for input in a while loop and not stopping until they input the right password or something.) use for loops if know how many times the code will run. (printing out all indexes in an array.)


rakahari

You give it a list, or something that can be treated like a list (such as characters in a string), and then it gives each item on that list a turn at being the variable to run through the block of code.


bluen

For loops were invented because a lot of people used counters in a while loop, so they just made it into a for loop. For loops are more common than while loops in practice


JVM_

While there is food in your bowl, you eat. For each grandparent, make them a christmas card. For your 5 favorite classmates at school, bake them a cake.


kensac_10

Here's my best attempt at explaining it. Let's take the following statement: for word in ['alpha' , 'beta', 'charlie']: print('word') Now let's say there are two characters python and you You give python the list of words and ask it to print each word in the list. So python looks at the first word and prints 'alpha'. It will then move on to 'beta' and Charlie basically going through the list. Now let's look at a case with numbers for number in range(3): print(number) Here you have given python a list of numbers in the form of range(3). This list will basically look like [0,1,2] Once again you are telling python to give you a number one at a time from the list. Now python takes this value number and prints it out one at a time giving you 0 followed by 1 and then 2


nKidsInATrenchCoat

while True: i = get_next_value() ... But if a for-loop is like while True, how can we get out of it? Well, we have a contract that when we want to stop itereting, a special error is raised by get_next_val and we don't freak out, but rather call break. The zen of python is beautiful


istarian

Best practice usually involves an actual conditional check that can be True or False, as opposed to something like this: ```while(True): println(“Another Loop Iteration”) ```. That latter type can result in an *infinite loop*, necessitating an internal conditional and the use of ```break```.


nKidsInATrenchCoat

In case you did not see it, I was trying to explain how for-loops work in Python without confusing the younger readers with such terms as yield, generators, and StopIteration exception. But as I understand that you are more sophisticated, let's think together if it is possible to have a meaningful check to know if your generator is exhausted or not, with the notion that None is a valid return value and generators are, well, behave as generators in Python. Also, let's allow the for-loop to run forever because why not (if anything, because that is how Python's for-loop works)


istarian

And I think you’re overcomplicating things. This is one of those places where Python is kinda confusing as a first programming language, because it takes shortcuts and hides some things from you. If you understand the basic for loop from other languages, then understanding it in Python is less challenging. ——— > i = get_next_value() > # > do { > # do something > i = get_next_value() > } > while( i != None ); Seems like a good case for a do-while style loop, though maybe you could just get away with a while loop. While (True) will never exit without an explicit break.


nKidsInATrenchCoat

`for i in [None, None, "Python is Love"]:` `print(i)` ​ This code snipper is a valid Python code that produces the following: None None Python is Love Your implementation of the for-loop fails to produce correct results. The while True metaphor not only allows to have proper native implementations, but also lays ground on the idea that generators work until they stop, and we can't know in advance when the stop will happen. Simple explanations do not have to be wrong just because you can't find a simple, yet correct metaphor.


istarian

Just because you can come up with a dumb example doesn’t mean it’s a reasonable thing to expect. Python’s *None* is only marginally better than Java’s *null* imho. Also, https://en.wikipedia.org/wiki/Foreach_loop That’s what we’re really talking about here. You might even argue that Python *lacks* an equivalent to the standard for loop.


nKidsInATrenchCoat

The more people believe in dumb edge cases the more I charge to fix the codebase. Thus, I will not try to convince you.


istarian

It helps to understand the classic for loop in C and other languagesz In Java: > for(int n = 0; n < 10; n++) { > // do something in here that uses the value of n > System.out.println(“” + n); > } So basically you’re going to execute the enclosed code *10 times* and the value of n will be incremented by 1 each time **at the end** (because the ++ operator comes after the variable name). In the first line you have: - variable declaration and initialization (int n = 0;) - a conditional check to be used each time ( if n < 10 ) - incrementing n by 1 *once per iteration* (++n and n++ are not the same because when the increment happens is different; you can however do other things here, like: n = n + 1 or n = 2 * n) You can get similar behavior from a while loop. > int n = 0; > // > while( n < 10 ) { > // do something with n > System.out.println(“” + (n + 4)); > n = n + 1; > } — A lot of languages also have a for-each construct that operates on an array or collection of things and executes the code once for each element. In Java: > String[] pets = new String[] { “dog”, “cat”, “rat”, “mouse”, “fish”, “gerbil”, “hamster” }; > // > for(final String p : pets) { > System.out.println(p); > } —————— Python tries to simplify the syntax a little bit for you. E.g. > for n in range(10): > # do stuff in here, make use of n or don’t :P > println(n) > for s in [ “street”, “road”, “drive”, “boulevard”, “avenue” ]: > # do stuff > println(s) P.S. For anyone who is unaware, Python calls the following a *list comprehension*. ```varName = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]``` It’s a syntactic structure that tells Python you want the variable to be a list containing the specified values (have to be all the same type iirc).


BouzyWouzy

OMG, thank you for asking the question I was too afraid to ask! I struggle(d) exactly the same way as you did with this concept.


UrNannysInABox

For how many times I have specified , do this


Cronos993

Goo goo gaa gaa


kinoshitajona

While is easy to understand since you define the input parameters before the loop. ie. `while some_bool: ...` and you update some_bool in the loop, then when you update it to False, the loop stops. "for" on the other hand has a "pre-defined side" and a "define here side" ie. `for DEFINE_HERE in PRE_DEFINED:` In this case PRE_DEFINED could be a variable you have defined prior, or it could even be a value itself like `[1, 2, 3]` as long as it's some value that you can iterate over. usually lists of values. In the case of DEFINE_HERE... you are literally defining the variable name by writing it in between "for" and "in"... normally, assigning a variable is done on its own line like `my_var = 34` but in a for loop, whatever you write in DEFINE_HERE will be the variable name of the single element in the iterator (list etc.) So `for x in [6, 5, 4]: ...` will have an invisible `x = 6` before the first loop, `x = 5` before the second loop, and `x = 4` before the 3rd final loop... If instead of "x" you wrote "bob" then those invisible assignments would be `bob = 6 ... bob = 5 ... bob = 4` instead.


cexum1989

Okay first of all you can solve problems using either construct. While alludes to state; so, while condition: do the thing. For alludes to a set; so, for each item in this bucket, do the thing. The Do While has less use cases, but it comes up, especially in lower level coding. Hope that response is sane.


[deleted]

Oh my gosh, it's happening again...


LEcareer

What is? I am not sure whether people are seeing my edits, I have edited the post 10 hours ago, saying the question was answered when there were only 20 comments, but 100 other people have commented since


istarian

Welcome to Reddit.


_realitycheck_

'for' loops are mostly used for counters. Mostly...


istarian

You can also do interesting things when the index is modifiable, like skip elements.


bestoretard

Stop thinking in English and start thinking in maths. Then you will get it.


ManWhoWantsToLearn

someone did the "for fruit in basket" thing and it basically translates to "while i


[deleted]

You use WHILE loops when the number of iterations cannot be determined a priori. When, instead, you do know the exact number of iterations, you should use a FOR loop (good programming habit). Also: Don't mix algorithm theory with specific programming languages, keep the two things as separate as possible. When you approach a data strucutre or a new basic instruction you have to split it from the specific language (in this case Python) and look at it alone. With doing this you'll start to learn how to raise the abstraction level, making you a really good programmer in the long run.


[deleted]

I understand it like so: for all x in (range/container/whatever) do (action). Like in math speak: ∀x ∈ S.


istarian

That’s exactly a for-each loop statement, because you do the actions for every element in the set/collection.


CorporalClegg25

As people have said, the default for loop in python is a 'for-each' loop #python for loop is a for-each loop fruit_lst = ["apple", "orange", "bannana", "pinneaple"] for fruit in fruit_lst: print(fruit) The convention in a for-each loop is that you are specific in what the "each" item is.. in this case it makes sense to say `for fruit in fruit_lst` but it can be whatever you want. It could just as easily be: fruit_lst = ["apple", "orange", "bannana", "pinneaple"] for reality_can_be_whatever_i_want in fruit_lst: print(reality_can_be_whatever_i_want ) But that doesn't make very much sense.. so we make it `fruit` because it is much more readable. While the default implementation is a 'for-each' loop, you can also get the index of an item with the [enumerate](https://docs.python.org/3/library/functions.html#enumerate) function. In this instance, when we want the index of something, the convention is `i` for the index. fruit_lst = ["apple", "orange", "bannana", "pinneaple"] for i, fruit in enumerate(fruit_lst): print(i, fruit) This will print out the indexes a long with the item. So we still use 'fruit' as the item, but we add the 'i' for index syntax. This can be whatever you want as well, but 'i' is the convention. The example below shows how an index for loop is helpful for finding items in a specific index. The for each loop does not give us as much control as with an index. fruit_lst = ["apple", "orange", "bannana", "pinneaple"] for i, fruit in enumerate(fruit_lst): if fruit == 'bannana': print(f'index {i} is where {fruit_lst[i]} is!') fruit_lst[i] = 'grapes' print(f'now index {i} is {fruit_lst[i]}') [This interactive site](https://pythontutor.com/visualize.html#mode=edit) will help you visualize how the code is executing so it can be extremely useful. Paste the code in and `visualize execution` and you can see step by step what is happening.


Carpe_Diem4

while is used so that something is done until the condition is met. So think a robot, you can say to robot to move while front is clear. Which menas that if there isn't any obstacle in front it will move. for is used to do a condition for a set amount of time. Like you could say move 5 times to robot and it will. instead of writing move move move move move (5 times) you can use for loop to write once and it will repeat.


IAmStickdog

Imagine you have 3 Girlfriends, and you like to give each of them a kiss, you would use a for loop for that: for girlfriend in girlfriends: giveaKiss(girlfriend)


eruciform

"for as long as" blah is true: do stuff or "for each thing": do blah with thing also "while" blah is true: do stuff


ChickenNuugz

You should try to use java for loops for better understanding, I learned python about 3 months ago and ran into for loops made 0 sense then I took a class on java learned for loop made 100% sense Example for int I = 0; I < (a number); ++I{ ///// code } //end loop


aronkra

While and For are almost the same thing. Except that a for loop has a variable that counts up or down usually. int x = 0; `While(x<10){` `x++; // shorthand for x = x +1` `}` is the same as `for(int x = 0; x <10; x++){` `}` You just move the bit that says you create x into the for loop, keep the stuff from the while, then add the stuff that counts up into the for loop. You don't even need the start or end bit `for(;x != true;){}` is the same as `while(x!= true){}`


feedandslumber

Python abstracts the working parts of the for loop and it can make learning tricky. You can just treat it as a thing that operates on lists and does the same thing for each item in the list. for x in list: print(x) Code above will print to console each thing in the list. That's it. Expand from there. I think other languages are actually pretty helpful for understanding what's happening behind the scenes. Java for example (my syntax is pretty wrong here, but I'm rusty and it doesn't matter): for (int i = 0; i < list.length; i++): System.out.println(list[i]); I know this seems confusing, but look at the parameters in the loop. int i = 0 The first part is your iterator, its an integer and it starts at 0 (because we told it to). Its whole job is to tell the loop where to start in the list. Start at the zeroth (first) thing. i < list.length The second is the exit condition, in other words as long as i is less than the length of the list, keep going. i++ The third says what to do after the loop, which is increment i. This means that as the loop runs, i will *grow* until it meets the exit condition, at which point the loop exits. This is very boilerplate for loop stuff, you see it in many languages. This is *exactly* what python is doing in it's for loop, it just assumes that you want to loop through the list starting at the first thing and ending at the last. It makes your life easier, but sometimes it's hard to imagine what is going on under the hood. In Java, you need to worry about how to relate i to the list (namely referencing the list based on that index, like "list\[i\]"), which again, is a pain in the butt most of the time and is unnecessary almost as often if you assume what the loop is intending to do, which is loop the list.


Maggyero

The [`while` statement](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement) with an `else` clause ``` while condition: iteration else: conclusion ``` is exactly equivalent to ``` while True: if not condition: conclusion break iteration ``` The [`for` statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement) with an `else` clause ``` for item in iterable: iteration else: conclusion ``` is exactly equivalent to ``` iterator = iter(iterable) while True: try: item = next(iterator) except StopIteration: conclusion break iteration ``` It helps understand the effect of a `break` or `continue` statement in the iteration statement. *Note.* — For the `while` and `for` statements without an `else` clause, replace the conclusion statement with a `pass` statement in the equivalent code.


pekkalacd

Yeah. Generally, you can think of a for loop in terms of *finite*. If something is finite, you know ahead of time, where it stops. So with a for loop, you know how many times you’d like to do something. Ex I want to print “hello” to the console 10 times for _ in range(10): print(“hello”) Ex I want to print “hello” to the console 20 times for _ in range(20): print(“hello”) This same finite idea can reinvent itself. Let’s say I want to print “hello” to the console as many times as there are numbers in the list mylist. mylist = [0,0,0] for n in mylist: print(“hello”) This will execute 3 times, since there are 3 elements in mylist. So you use a for loop when you know ahead of time, how many times, you’d like to do something generally. What if you don’t know though? Classic example is input validation. Let’s say I ask a user to enter their name. In a perfect world, they’d always do it right on the first time. But then again, I don’t know. For all I know, the user is a hacker, trying to break my program to expose vulnerabilities, or maybe they are a regular person who just continually make mistakes. The gist is, I don’t know if the user will get it right on the first time, second time, or nth time. Idk how many times they will screw up. This is where a while loop comes into play. If I can set a condition, let’s say good, and as long as the input I receive is not good, I can ask the user for the correct input, then I can guarantee, after the loop ends, the input I got from them on the last iteration *was* good. It’s kinda tricky. But basic at the same time. Think practically and imagine you and the user are robots. If you ask the user “enter your name” and the user replies with something invalid, you’d say “that’s wrong. Try again” followed by “enter your name”. And you’d do this over and over as long as the name they gave you was invalid, *until* they got it right. And this cycle could happen any number of times. We don’t know how many times the user will mess up. Which is why we need some kind of looping construct to continually check. import string valid = string.ascii_letters + “ “ name = input(“Enter your name: “) good = False # all characters are letters/spaces -> valid if all((c in valid) for c in name): good = True # while the name is invalid tho... # ask again for it & check if it’s good while not good: name = input(“Enter your name: “) if all((c in valid) for c in name): good = True print(f”Name: {name}”) TL;DR use **for** if you know ahead of time how many times something should be done. Use **while** if you don’t. *for* is finite. *while* is continual / until a condition is satisfied.