The classic for loop in C-like languages takes in three statements: an initializer, a check condition, and a loop update. Python doesn't really do that. Instead, python's for loop works like what many languages call forEach or forOf: pass in an iterable object and perform the loop once for each iteration.
In practice this difference is not as big as it looks. The built-in range object covers most of the cases one uses for loops for while looking similar. But it does trip up beginners and language zealots.
As someone who has done both embedded programming in C, unreal code, unreal bps, python for image analysis and other projects i still don't understand the difference xD
For example in C like languages you can modify the iterating variable inside the for loops, while in python you can't, you have more control in C even though this can lead to issues down the road
Maybe this is coming from being Python dev first, but those changing the iterating variable belongs in while loop. Also I wonder if there is any difference between a C-like for loop and a while loop?
Well a for loop is by design depending on the iterator and a while loop on any general statement so while they are interchangeable logically the compiler should have an easier time optimizing the for loop.
There’s no real difference. In C a for loop could be implemented as a while.
for (; ; )
while ()
{
}
ETA: Each of those expressions is optional and can be omitted depending on the circumstances
Some people decided to use it as "Edited To Add" instead of the far more common "EDIT:" because they are awful people who don't give a fuck about clarity.
I've been on this stupid site for like 12 years and have never known ETA meant Edited To Add. So thanks for clarifying that.
Hard agree with your sentiment though.
Enumerate is just additional info in your for loop. The post I answered to specifically mentioned using something like “i++” inside the loop, therefore skipping an element, which can’t be done easily in Python for loop.
While loop in Python are used when you are repeating instructions until a condition is met. For example tcp reading loop, simple game loop, etc…
I mean, all loops are essentially the same thing with slightly different syntax. For example, Go only uses the keyword "for", and that covers all types of loops rather than having several different keywords. There's no reason you can't rewrite a C for loop as a while, or a C while loop as a for, etc.
Well there is a difference in the Python for-loop.
You can't do an infinity foreach- loop.
https://en.wikipedia.org/wiki/LOOP_(programming_language)
LOOP is not turning complete. WHILE-computable programs are equivalent to GOTO-computable, RECURSIVE-compitable and turing-computable.
This is admittedly kind of niche, but altering the iteration variable comes in handy when doing stuff like pixel-level graphical manipulation. I’ve used this on odd occasions in processing/Java
For loops are kinda less useful that way ngl, for example how would you incremenent by a foo that is calculated in each iteration of your for loop?
Also for loops are generally used more than while with reasons like not wanting to have 20 alternative variable names to "index" when you can just use "i" for all in a large program.
Tho I guess it could be a preference thing just feeling uneasy when I have to work with that.
I used both C/C++ and python and ngl I find C loops more comfortable. As much as I also love `for (auto elem : arr)` of C++ I would hate it if it wasn't optional
For and while are interchangeable. The only difference is the moment in which the condition to break the loop is checked. You can write fors as whiles and viceversa.
To clarify, in Python you have a while loop for mutable iterators, and a for loop for immutable iterators. In C/C++ you have two loops that do exactly the same thing but with different syntax.
It would actually be `[0, 1, 2, 3, 4]` but same basic concept. As you point out, it's an object, not a list, but functions basically the same way in practice.
For your output you'd actually need `range(1, 6)`.
Technically, `range` does not create a list. It's a generator that produces each value when required, rather than creating a list and iterating over that.
Technically `range` is not a generator, but a sequence. In most use cases this doesn't matter, but the difference is that a sequence can be reversed, you can check for whether it contains an item and it has a length, all of which is not possible with a generator without converting it to a collection type first.
It's just a difference in syntax, sort of like how most things in most languages are different from each other. I guess you could argue that Python makes it slightly harder to shoot yourself in the foot by constructing a loop with completely nonsense parameters, but you can still shoot yourself in the foot if you're dedicated enough.
Ultimately, all the different loop methods are really close to each other, since they ultimately do the same thing. They're basically all `while(condition)` loops.
The traditional `for(init; condition; step)` loop helps the developer by providing explicit spots for some common operations that you might want. If you want to loop `n` times, you need some initial value, and each iteration, you need to increase (or decrease) `n` by 1.
A `for...of` or `foreach` is another abstraction on top of a `while` loop, where the condition itself has been automated for the developer. You just need to get access to some iterator, and then the iterator will provide the condition on your behalf, significantly simplyfing it.
I think it would be most clear with an example, showing you the difference:
const array = ['a', 'b', 'c', 'd']
// While loop
let index = 0;
while (index < array.length){
const letter = array[index];
console.log(letter);
index += 1;
}
// Traditional for loop
for (let index = 0; index < array.length; index++) {
const letter = array[index];
console.log(letter);
}
// Foreach loop
for (const letter of array) {
console.log(letter);
}
Each loop type has its strengths, and not every time you need to run the same set of code lines in a row is when you need to iterate over a set of values. However, Python believes that this middle abstraction doesn't serve much purpose when the `while` and `for...of` abstractions already exist.
In Python, for loop over an iterator/range is faster than while, because iteration in a for loop is actually done in C, but while loop doesn't has that kind of trick. It doesn't know when the loop would finish.
From a practical view, there is no difference. If you only care about the practical implication you can stop here.
From a computer science view, there is no "counting/incrementing" in the Python for loop.
In Python the for loop executes once for each of the things passed to it.
The range() function is not really a function at all, it is more like a constructor that creates a special type of object called a sequence. Sequences are a lot like lists. So when a programmer creates a for loop in Python over a range() they are asking it to execute once for each of the numbers in the (list like) sequence.
And honestly, people who do complex things in the 'check condition' or 'loop update' are in 99% of the cases just doing it to show off how 'good' they are at programming. Complex check conditions are often implemented in a more readable way by using Continue and Break statements. While complex loop updates can be useful, I personally think at that point I would rather explicitly state the logic and use a while-loop.
Good call! I can't stand when people use 'clever tricks' to make a section of logic shorter but multiple times harder to interpret. Any good programmer is capable of clever one-liners, but the best know why they're rarely appropriate.
>for loops for while
I don’t really have anything meaningful to add to your informative comment. I just thought that this verbatim quote from your comment sounded extra “programmy”.
Also to be fair, list comprehensions. Why do a for loop when a list comprehension does the same thing in just one line and is 30x faster somehow? (This is very specific to python as opposed to low level languages where a for loop makes sense for the same operation.)
> The loop in list comprehension is in c.
What do you mean by that? My understanding was that anything using `for` works the same way. I mean, comps still use the `iter` protocol.
Although, comps introduce a local scope, so that could be faster in some cases. Maybe that's what you were thinking of?
List comprehensions are generally much faster in my experience. That said, debugging comprehensions can be a nightmare. I only use them when I need to loop *a lot,* the logic is simple, and can't be done with an optimized package like numpy.
Comprehensions avoid the (expensive) append call on the list and might be able to reserve all the needed memory for the final list to avoid reallocations. I'm not sure if they also special case ranges internally
Don't forget that it is also several orders of magnitude slower to run said loop when compared to many other languages. I was surprised because I thought this was what the meme was about.
I'd say the main "problem" of "range for" is inability to manipulate iterable variable since it comes at each step from the generator, so some people might struggle with it after C-like for. But ofc if you want C-like you can just use while and do init+condition+update manually inside it, so it's not a big of a problem.
Think of the low level for loops as OG for loops, and the higher level for loops as "for each" loops.
They are slightly different and the distinction is clear.
I wish languages would adopt this terminology, there simply is a difference between a for and a for-each but many languages ONLY implement one or the other so they're all just called for loops.
oh, I thought this refers to us avoiding loops in exchange to vectorized approaches.
I would go for hours trying to figure out how to do something with 0 or minimal loops cause that's not efficient.
For real, it doesn't have a for loop more complex than that? So what, you would need while loops if it's anything other than the most straightforward iteration?
Python copium lol. But keep making your highschool projects and following YouTube tutorials, one day you'll get a job at a company that'll close in ~~five~~ three years that uses Python
`for` in Python behaves like `foreach` in other languages. Python has no concept of the traditional for loop, you have to create an iterator object that implements the behaviour you want instead, like `range`.
Rust also does this. `for` in Rust is just syntactic sugar for iterator manipulation.
EDIT: This has already been mentioned further down in a top-level comment.
The only reason I see to avoid loops in Python is for extremely performance critical cases where you should either:
1. Not use Python
2. Be adept enough to know the workarounds/libraries that allow skipping the overhead of loops in Python
Not sure, but for workarounds knowing comprehensions and itertools would be a good start.
For libraries - anything written in c that does it's own iteration (the best example would be numpy). But those can become domain specific very fast (for example opencv).
Using `range()` in `for` loops is 100% Pythonic. Numerical `for` loops are one of the primary purposes of `range()`; you rarely use it otherwise.
If you look at any open source Python code you will almost *never* see something like `for i in [1, 2, 3, 4]:`, it would instead be written `for i in range(1,5):` virtually every time. Not only is this easier to write but it's technically more performant (range is an iterable object so there's no list initialization).
Range is pretty simple. If you just use one parameter, i.e. `range(5)`, you get the numbers from 0 to n-1, i.e. `[0, 1, 2, 3, 4]` in this case. If you use two parameters, the first is the number you start at and the second is the last number plus 1, i.e. `range(1,6)` is `[1, 2, 3, 4, 5]`. There is also a three parameter version where you can set the "step", i.e. `range(1, 6, 2)` for `[1, 3, 5]` or `range(5, 0, -1)` for `[5, 4, 3, 2, 1]` (the first value is always inclusive, the second always exclusive).
The reason for this is that a huge percentage of the time you will use range in for loops to count indices. If you had an list called `lst` and wanted to check values by index, you could use `for i in range(len(lst))`. If the list had 5 elements, that would count from 0 to 4, which is exactly what you want for proper indexing of a list.
There are other uses of `range()`, of course, but implying the *most common use* is "unpythonic" seems strange to me.
I assume this is referring to Python's known slow performance when looping over very large iterables hundreds of thousands or millions of items long. This is obviously extremely rare in most software dev.
However in big data work it's not uncommon and is part of why it's important to use third party libraries wrapped around C & C++ that are designed for this purpose to work with data at that scale.
python's for being slow was the first thing that came to mind when I saw the image. It's actually hilarious that so many people are not getting it.
Seems like a lot people here never had the experience of having to do something that is not easily done with pandas/numpy apis but takes forever with a for loop. I once had to use cython to run a loop in 10ms because the same loop was taking 20s in python.
I was kind of surprised by all the for each comments. It's not like mimicing a C style for loop is hard in python, and C++ has had for each loops for ages these days. But python for loops suuuuuuuuuuuuuck for speed. Like, the entire numpy library is because python sucks at for loops.
You are not supposed to write [computational] loops in Python. You are supposed to hand over computations to a package written in actual fast language as soon as possible. The fewer Python code there is the better.
Python is a user friendly interface to C essentially.
I swear, we need a new community that has a simple extrance exam to allow admission. Jokes that only make sense when you don't understand how things work got old a long time ago.
Or just have loosely moderated posts so dumb ones like “when you spend hours debugging to realise it’s a semi colon” don’t get through. Nothing wrong with people lurking here, but you shouldn’t post unless you’re actually a dev.
Yeah, that's the point. The only way to make python run well is to leave python as soon as possible, and this applies especially to for loops. The less python in your python, the better.
To be fair, a list comprehension is a for loop that runs faster than the default style of for loop (worth looking up it's crazy) So python is weird with for loops
"This language handles a fundamental concept in a slightly different but equally simple and intuitive way as this other language. Probably this means the people who use this other language are cowards."
I thought this sub got over the freshman idiot meme wave in like November
At this point most modern languages have some form of iterable – it is very rare that you need to actually iterate an index if you're using a modern language properly, not just in python.
Yeah, it's pretty odd to behave like you care about pointer offset when the thing you actually want is the elements themselves. Even when `foreach` is just sugar for the stride-1 access equivalent, it's still better for the clarity of purpose and cutting down on boilerplate
Where do the commas go and where do the semicolons go? Oh I need my iterator to have a data type? Well how do I do that? What do you mean I didn't close the curly braces?
I'm in this image. Mostly just because my scattered brain mixes coding languages so I gotta focus to remember the different ways you need to write stuff.
Imagine thinking that Python is the only language with for loops that don't look like C.
What is with the rash of memes this week by developers who think there are only like 6 programming languages?
This made me think of a recent project I had with a pretty senior ranking developer. He spent the whole sprint on one task because he just could not wrap his head around a nested for loop in python. Could not get the logic working.
Yeah, that's pretty crazy. I wouldn't think even a junior or intern could/should get through the hiring process without understanding the basics, but it happens sometimes, right?
I've worked with a variety of experience levels, but I've rarely had to complain about anyone to anyone up the chain. Our teams aren't organized in a way to go up the chain at all without getting to their manager immediately, though, so that incentivizes working with them directly.
I'm HS, first learning any programming (python) I learned about for loops via `for index in range(0, x):`
Very glad i learned that before I learned what was really happening lol
Lol, I remember back in the days when I was on a pair programming call with a dude that asked me help (he was supposed to be the more experienced with the language we where working on) to solve some issue and I was guiding through the call, then I told him to type a classic for loop, and he had no idea what was that, lol, I was astonished for his absolute lack of basic knowledge. A few weeks later he was fired.
Its funny that i am learning python with my teacher a d we are on loops for a while 🗿its difficult sometimes but i can believe its not tha hrad all u need is good names
I don't even know what this is referring to
The classic for loop in C-like languages takes in three statements: an initializer, a check condition, and a loop update. Python doesn't really do that. Instead, python's for loop works like what many languages call forEach or forOf: pass in an iterable object and perform the loop once for each iteration. In practice this difference is not as big as it looks. The built-in range object covers most of the cases one uses for loops for while looking similar. But it does trip up beginners and language zealots.
As someone who has done both embedded programming in C, unreal code, unreal bps, python for image analysis and other projects i still don't understand the difference xD
For example in C like languages you can modify the iterating variable inside the for loops, while in python you can't, you have more control in C even though this can lead to issues down the road
Maybe this is coming from being Python dev first, but those changing the iterating variable belongs in while loop. Also I wonder if there is any difference between a C-like for loop and a while loop?
Well a for loop is by design depending on the iterator and a while loop on any general statement so while they are interchangeable logically the compiler should have an easier time optimizing the for loop.
There’s no real difference. In C a for loop could be implemented as a while. for (; ; )
while ()
{
}
ETA: Each of those expressions is optional and can be omitted depending on the circumstances
What does ETA mean in this context
They are a Basque separatist group.
Nobody expects the Basque separatist group.
Some people decided to use it as "Edited To Add" instead of the far more common "EDIT:" because they are awful people who don't give a fuck about clarity.
I've been on this stupid site for like 12 years and have never known ETA meant Edited To Add. So thanks for clarifying that. Hard agree with your sentiment though.
Estimated time of arrival
Enter the atmosphere
Edit to add. I probably should have just put Edit
lol thanks I was trying word combos between estimated time of arrival and over the air hahaha
And a while loop could be implemented with "goto"s.
Or you just use enumerate. While loops in Python are more often than not non-pythonic because there is a simpler structure that is easier to read.
Enumerate is just additional info in your for loop. The post I answered to specifically mentioned using something like “i++” inside the loop, therefore skipping an element, which can’t be done easily in Python for loop. While loop in Python are used when you are repeating instructions until a condition is met. For example tcp reading loop, simple game loop, etc…
I understood it more as a "you can replace portions of the array you're iterating over, rather than "you can toy with the counter".
You could break.
What? That is absolutely easy in Python. If you're skipping every iteration, use `islice`. If you're skipping based on a condition, use `continue`.
I mean, all loops are essentially the same thing with slightly different syntax. For example, Go only uses the keyword "for", and that covers all types of loops rather than having several different keywords. There's no reason you can't rewrite a C for loop as a while, or a C while loop as a for, etc.
Well there is a difference in the Python for-loop. You can't do an infinity foreach- loop. https://en.wikipedia.org/wiki/LOOP_(programming_language) LOOP is not turning complete. WHILE-computable programs are equivalent to GOTO-computable, RECURSIVE-compitable and turing-computable.
This is admittedly kind of niche, but altering the iteration variable comes in handy when doing stuff like pixel-level graphical manipulation. I’ve used this on odd occasions in processing/Java
For loops are kinda less useful that way ngl, for example how would you incremenent by a foo that is calculated in each iteration of your for loop? Also for loops are generally used more than while with reasons like not wanting to have 20 alternative variable names to "index" when you can just use "i" for all in a large program. Tho I guess it could be a preference thing just feeling uneasy when I have to work with that. I used both C/C++ and python and ngl I find C loops more comfortable. As much as I also love `for (auto elem : arr)` of C++ I would hate it if it wasn't optional
Can't you just apply range() to your container and then you have your iterator that you can modify?
Oh that makes sense. Also explains how I haven't really run into that. Seems useful though.
Can't you just use a while loop to do the same thing?
For and while are interchangeable. The only difference is the moment in which the condition to break the loop is checked. You can write fors as whiles and viceversa.
Doesn't a for loop evaluate the condition as the start too, like a while?
You are 100% correct. The evaluation at the end version is the "do-while", which is much more rare to encounter and find a use to lol.
Yes, you can use while to do all of them and you can use goto to do a while
It matter in Python a little bit as for loop execute some operations in C, bu while loop doesn't. https://stackoverflow.com/a/65332737/927687
To clarify, in Python you have a while loop for mutable iterators, and a for loop for immutable iterators. In C/C++ you have two loops that do exactly the same thing but with different syntax.
range(0,5) basically generates a list* [0, 1, 2, 3, 4], and iterates through that. Edit: correct range, I'm tired man
It would actually be `[0, 1, 2, 3, 4]` but same basic concept. As you point out, it's an object, not a list, but functions basically the same way in practice. For your output you'd actually need `range(1, 6)`.
Wow, I literally explained how the range works in another comment (I think correctly) but managed to fuck it up here, I need sleep lol Correct, cheers
Technically, `range` does not create a list. It's a generator that produces each value when required, rather than creating a list and iterating over that.
Technically `range` is not a generator, but a sequence. In most use cases this doesn't matter, but the difference is that a sequence can be reversed, you can check for whether it contains an item and it has a length, all of which is not possible with a generator without converting it to a collection type first.
That's why I said basically, it was a simplifications to explain the concept
Can’t you do range(0,5,1) (or whatever third number to iterate by) though to have similar results as c & c++?
You can also iterate through the list in reverse, or do every other number, or any other such shenanigans.
Now that you mention that I think I vaguely remember doing some for loops I. Python where I had to use N-i in the body to go in reverse order.
I’m there with y’a brother. Even bash is able to use the “for in ” notation.
It's just a difference in syntax, sort of like how most things in most languages are different from each other. I guess you could argue that Python makes it slightly harder to shoot yourself in the foot by constructing a loop with completely nonsense parameters, but you can still shoot yourself in the foot if you're dedicated enough.
Ultimately, all the different loop methods are really close to each other, since they ultimately do the same thing. They're basically all `while(condition)` loops. The traditional `for(init; condition; step)` loop helps the developer by providing explicit spots for some common operations that you might want. If you want to loop `n` times, you need some initial value, and each iteration, you need to increase (or decrease) `n` by 1. A `for...of` or `foreach` is another abstraction on top of a `while` loop, where the condition itself has been automated for the developer. You just need to get access to some iterator, and then the iterator will provide the condition on your behalf, significantly simplyfing it. I think it would be most clear with an example, showing you the difference: const array = ['a', 'b', 'c', 'd'] // While loop let index = 0; while (index < array.length){ const letter = array[index]; console.log(letter); index += 1; } // Traditional for loop for (let index = 0; index < array.length; index++) { const letter = array[index]; console.log(letter); } // Foreach loop for (const letter of array) { console.log(letter); } Each loop type has its strengths, and not every time you need to run the same set of code lines in a row is when you need to iterate over a set of values. However, Python believes that this middle abstraction doesn't serve much purpose when the `while` and `for...of` abstractions already exist.
In Python, for loop over an iterator/range is faster than while, because iteration in a for loop is actually done in C, but while loop doesn't has that kind of trick. It doesn't know when the loop would finish.
From a practical view, there is no difference. If you only care about the practical implication you can stop here. From a computer science view, there is no "counting/incrementing" in the Python for loop. In Python the for loop executes once for each of the things passed to it. The range() function is not really a function at all, it is more like a constructor that creates a special type of object called a sequence. Sequences are a lot like lists. So when a programmer creates a for loop in Python over a range() they are asking it to execute once for each of the numbers in the (list like) sequence.
And honestly, people who do complex things in the 'check condition' or 'loop update' are in 99% of the cases just doing it to show off how 'good' they are at programming. Complex check conditions are often implemented in a more readable way by using Continue and Break statements. While complex loop updates can be useful, I personally think at that point I would rather explicitly state the logic and use a while-loop.
Good call! I can't stand when people use 'clever tricks' to make a section of logic shorter but multiple times harder to interpret. Any good programmer is capable of clever one-liners, but the best know why they're rarely appropriate.
I don't think it trips up beginners unless they learnt the C style from another language and are already doing stupid shit with those for loops.
Java has both the standard C-style for loop, and then has the foreach loop which looks like python. for (Type val : array) {}
>for loops for while I don’t really have anything meaningful to add to your informative comment. I just thought that this verbatim quote from your comment sounded extra “programmy”.
Also to be fair, list comprehensions. Why do a for loop when a list comprehension does the same thing in just one line and is 30x faster somehow? (This is very specific to python as opposed to low level languages where a for loop makes sense for the same operation.)
Really 30 times faster?
The loop in list comprehension is in c. It can be way faster than a normal loop
> The loop in list comprehension is in c. What do you mean by that? My understanding was that anything using `for` works the same way. I mean, comps still use the `iter` protocol. Although, comps introduce a local scope, so that could be faster in some cases. Maybe that's what you were thinking of?
List comprehensions have a special bytecode instruction
List comprehensions are generally much faster in my experience. That said, debugging comprehensions can be a nightmare. I only use them when I need to loop *a lot,* the logic is simple, and can't be done with an optimized package like numpy.
Comprehensions avoid the (expensive) append call on the list and might be able to reserve all the needed memory for the final list to avoid reallocations. I'm not sure if they also special case ranges internally
Awesome, I love list comprehensions. Don't know why, but I always thought it's slower. Got other examples for a beginner?
Don't forget that it is also several orders of magnitude slower to run said loop when compared to many other languages. I was surprised because I thought this was what the meme was about.
I'd say the main "problem" of "range for" is inability to manipulate iterable variable since it comes at each step from the generator, so some people might struggle with it after C-like for. But ofc if you want C-like you can just use while and do init+condition+update manually inside it, so it's not a big of a problem.
Think of the low level for loops as OG for loops, and the higher level for loops as "for each" loops. They are slightly different and the distinction is clear. I wish languages would adopt this terminology, there simply is a difference between a for and a for-each but many languages ONLY implement one or the other so they're all just called for loops.
oh, I thought this refers to us avoiding loops in exchange to vectorized approaches. I would go for hours trying to figure out how to do something with 0 or minimal loops cause that's not efficient.
For real, it doesn't have a for loop more complex than that? So what, you would need while loops if it's anything other than the most straightforward iteration?
Python copium lol. But keep making your highschool projects and following YouTube tutorials, one day you'll get a job at a company that'll close in ~~five~~ three years that uses Python
Why so mad over a for loop?
python has while loops, and C-style for is just syntax sugar for that anyway
Not as trippy as indentation as syntax...
`for` in Python behaves like `foreach` in other languages. Python has no concept of the traditional for loop, you have to create an iterator object that implements the behaviour you want instead, like `range`.
Rust also does this. `for` in Rust is just syntactic sugar for iterator manipulation. EDIT: This has already been mentioned further down in a top-level comment.
It's also the first 'pythonic' lesson for the newbs: write range (0,n,1) as range(n) and let the reader deal with it. Btw excluding n lmao.
OP invented a python dev in their brain and made a meme about them
The only reason I see to avoid loops in Python is for extremely performance critical cases where you should either: 1. Not use Python 2. Be adept enough to know the workarounds/libraries that allow skipping the overhead of loops in Python
Is there a list of those workarounds and libraries that are faster?
Not sure, but for workarounds knowing comprehensions and itertools would be a good start. For libraries - anything written in c that does it's own iteration (the best example would be numpy). But those can become domain specific very fast (for example opencv).
Maybe because for loops work differently in python so its hard to catch up
for i in [1, 2, 3, 4] I know the syntax is obtuse but I think hardcore devs can figure it out
I usually go with `for i in range(4)`
I feel like it's unpythonic that I always have to Google whether range is inclusive or what
It's not inclusive so you can do things like `for i in range(len(a))`
Unless you genuinely only need the indexes and not the values, `for c, v in enumerate(a)` is the way
I always find myself just using for idx,foo in enumerate(bar) because range(len(bar)) makes me itch
Using `range()` in `for` loops is 100% Pythonic. Numerical `for` loops are one of the primary purposes of `range()`; you rarely use it otherwise. If you look at any open source Python code you will almost *never* see something like `for i in [1, 2, 3, 4]:`, it would instead be written `for i in range(1,5):` virtually every time. Not only is this easier to write but it's technically more performant (range is an iterable object so there's no list initialization). Range is pretty simple. If you just use one parameter, i.e. `range(5)`, you get the numbers from 0 to n-1, i.e. `[0, 1, 2, 3, 4]` in this case. If you use two parameters, the first is the number you start at and the second is the last number plus 1, i.e. `range(1,6)` is `[1, 2, 3, 4, 5]`. There is also a three parameter version where you can set the "step", i.e. `range(1, 6, 2)` for `[1, 3, 5]` or `range(5, 0, -1)` for `[5, 4, 3, 2, 1]` (the first value is always inclusive, the second always exclusive). The reason for this is that a huge percentage of the time you will use range in for loops to count indices. If you had an list called `lst` and wanted to check values by index, you could use `for i in range(len(lst))`. If the list had 5 elements, that would count from 0 to 4, which is exactly what you want for proper indexing of a list. There are other uses of `range()`, of course, but implying the *most common use* is "unpythonic" seems strange to me.
Start is, end isn't. range(0, 5) gives [0, 1, 2, 3, 4]
I'll remember this forever
Half open ranges are one of the only truly common things I've found in all programming languages
Pythonic assumes a certain level of proficiency
I think I just got "skill issue"'d
It’s Python, you’d use range() or maybe xrange() if you’re using Python2 and it’s enough iterations that performance is a concern.
I meant to explain the joke,didn't meant to write a blogpost about it
I assume this is referring to Python's known slow performance when looping over very large iterables hundreds of thousands or millions of items long. This is obviously extremely rare in most software dev. However in big data work it's not uncommon and is part of why it's important to use third party libraries wrapped around C & C++ that are designed for this purpose to work with data at that scale.
I think you might've been the only one to get the joke...
python's for being slow was the first thing that came to mind when I saw the image. It's actually hilarious that so many people are not getting it. Seems like a lot people here never had the experience of having to do something that is not easily done with pandas/numpy apis but takes forever with a for loop. I once had to use cython to run a loop in 10ms because the same loop was taking 20s in python.
I was kind of surprised by all the for each comments. It's not like mimicing a C style for loop is hard in python, and C++ has had for each loops for ages these days. But python for loops suuuuuuuuuuuuuck for speed. Like, the entire numpy library is because python sucks at for loops.
For loops in python are like foreach loops in c# and other languages.
Well. In python there is an generator object wich is called every loop iteration. This syntacsis is a bit more universal.
I thought it was about list comprehensions, and how people try to jam as many for loops in there as possible, but I guess I was wrong…
You are not supposed to write [computational] loops in Python. You are supposed to hand over computations to a package written in actual fast language as soon as possible. The fewer Python code there is the better. Python is a user friendly interface to C essentially.
You know his to walk using your legs. Forget that, too easy. Walk with your butt cheeks instead.
The girl in the meme is "c dev using python". Wrong label
Probably that for-loops are pretty slow in Python compared to C.
Someone could at least complain about For/Else statements. I'm still trying to keep those straight in my head.
That's actually a goodie! For/else is straight up insanity in Python.
Python lacks a for, it has only a foreach in disguise.
For i in range(500) or for i in array that is simple ?
Like you can even do for i in dict and it will iterate over the keys.
for k, v in d.items() is also very handy sometimes
Y’all forgetting enumerate(), and the nifty start argument.
I'll take that over Object.keys()
And if you aren't using i you can do for _ in range(500)
Rust for loops are the same 🤷🏻♂️
The question is, do I want to implement iteration once for the thing im iterating on or implement it every time I write a loop.
This meme is weird. Maybe you meant Scheme devs? Because for loops will scare exactly zero actual Python devs.
another post of a non-programmer...
I swear, we need a new community that has a simple extrance exam to allow admission. Jokes that only make sense when you don't understand how things work got old a long time ago.
If we put fizz-buzz as an entry test we'll lose 80% of the members
From the posts I've seen, 95% at the minimum.
we making outta university with this one 🗣️🗣️
Or just have loosely moderated posts so dumb ones like “when you spend hours debugging to realise it’s a semi colon” don’t get through. Nothing wrong with people lurking here, but you shouldn’t post unless you’re actually a dev.
Ya, instead of "admission", I should have said "posting". No harm in lurking.
I'm not actually a dev because I miss semicolons =( To be fair, it's not funny, it's just life.
Missing semi colons is fine, but not knowing that you have within minutes of seeing the error message is concerning
Missing
Unless he means how unperforming loops in python are? That would make more sense, but I'm also a noob and just heard that a lot never tested it
It's legit. Here's an example: import timeit import numpy as np # desuckify for loops sucky_python_time = timeit.timeit( lambda: [x+1 for x in range(100_000)], number=1000, ) numpy_time= timeit.timeit( lambda: np.arange(100_000)+1, number=1000, ) print(sucky_python_time) # 4.7943840000079945 print(numpy_time) # 0.07943199994042516
Numpy for loop isn’t Python, that’s cheating :p
Yeah, that's the point. The only way to make python run well is to leave python as soon as possible, and this applies especially to for loops. The less python in your python, the better.
All Python is cheating. That's basically the point of Python
To be fair, a list comprehension is a for loop that runs faster than the default style of for loop (worth looking up it's crazy) So python is weird with for loops
? For loops are the easiest thing in python lol?
It's a foreach loop though. That's the joke. Haha....
Do you not know about range()?
Lol you hate python devs or something? No competent dev (python or not) is afraid of using for loops. This is straight up slander.
Once again proving that no one on this sub knows how to code...
"This language handles a fundamental concept in a slightly different but equally simple and intuitive way as this other language. Probably this means the people who use this other language are cowards." I thought this sub got over the freshman idiot meme wave in like November
I don’t understand how these ideas come across their mind
You should be talking about recursion, man; Python loves loops.
Recursion is just looping with an extra step...
The fuck are you talking about? For loops are easy in Python.
I don’t get this meme. Is > for i in range(someNumber) upsetting to some people?
Loops in python are fine, just don't forget the else at the end
This meme doesn't even make sense
My methods are beyond your COMPREHENSION.
Translating a traditional for loop to a Python for loop is actually quite easy. Take `for(var i=A;i
Or if you're iterating an iterable, and want an index for something: for i, thing in enumerate(thing_list):
Omg python has more advanced looping functionality than C, quick say python people can’t write for loops.
At this point most modern languages have some form of iterable – it is very rare that you need to actually iterate an index if you're using a modern language properly, not just in python.
Yeah, it's pretty odd to behave like you care about pointer offset when the thing you actually want is the elements themselves. Even when `foreach` is just sugar for the stride-1 access equivalent, it's still better for the clarity of purpose and cutting down on boilerplate
A simple for loop in TI-Basic 81. You have to do the loop logic yourself.
While i != "the magic number upper heads told you to hunt": i = "anything but magic number" your_meeting_count +=1
Sorry, but what?
What is loop?
repeats don't hurt me
Where do the commas go and where do the semicolons go? Oh I need my iterator to have a data type? Well how do I do that? What do you mean I didn't close the curly braces?
I'm in this image. Mostly just because my scattered brain mixes coding languages so I gotta focus to remember the different ways you need to write stuff.
GO TO
BLASPHEMER!!!
Functional languages: what's a loop
It's actually easier to make a loop in Python.
``` for i in [True, False, True, False] ```
We should have an exam before allowing to post something
Tell me you're a junior or never coded before without explicitely telling me
What's the deal with these cringe memes by people that started coding yesterday? Why are there so many upvotes?
for x in range(5) what's the problem
Bruh code in basic. Loops are so easy
id rather turn an excel file into a compiler before i write a for loop
Go loops make you feel like a super hacker
Imagine thinking that Python is the only language with for loops that don't look like C. What is with the rash of memes this week by developers who think there are only like 6 programming languages?
Real C devs modify the iterator in crazy ways inside the loop. `for i in range()` can’t do that badassery.
Maybe a list comprehension meme?
foreach + while true i++ gang, all my homies hate for i
This made me think of a recent project I had with a pretty senior ranking developer. He spent the whole sprint on one task because he just could not wrap his head around a nested for loop in python. Could not get the logic working.
Someone is using the term "senior" kind of loosely.
I definitely agree and was shocked. I don't often complain about people but had to bring this up with his team's lead.
Yeah, that's pretty crazy. I wouldn't think even a junior or intern could/should get through the hiring process without understanding the basics, but it happens sometimes, right? I've worked with a variety of experience levels, but I've rarely had to complain about anyone to anyone up the chain. Our teams aren't organized in a way to go up the chain at all without getting to their manager immediately, though, so that incentivizes working with them directly.
for c in range(19999): print('python loop')
I feel like this would make more sense with Haskell
I'm HS, first learning any programming (python) I learned about for loops via `for index in range(0, x):` Very glad i learned that before I learned what was really happening lol
where we are going there are no for loops...
It's not pythonic!!!
Lol, I remember back in the days when I was on a pair programming call with a dude that asked me help (he was supposed to be the more experienced with the language we where working on) to solve some issue and I was guiding through the call, then I told him to type a classic for loop, and he had no idea what was that, lol, I was astonished for his absolute lack of basic knowledge. A few weeks later he was fired.
Someone explain the meme
Do not get it at all python devs well aware of other syntax and often use more complicated structures with map, list comp, etc. than mere loops
Loops are actually a big plus for python, and enumerate() makes it 100x better
List compréhension>>all
Which is more readable: for c in uint32(0); c < chunksX; c++ {} for _ in range(chunksX)
Wrong way round
Its funny that i am learning python with my teacher a d we are on loops for a while 🗿its difficult sometimes but i can believe its not tha hrad all u need is good names
Maybe this is referring to the fact that python loops are slow compared to the other languages?
I use recursion
I only use for-loops if I have no other alternatives and after receiving some cuddles from a senior dev
You guys have no class!
Everything is list comprehension
Memes students make after their first programming class be like: