Loop like a native: while, for, iterators, generators
Why Stack Overflow recommends it
Stack Overflow users link it when answering beginner and intermediate Python questions where the asker is looping by index or breaking out of nested loops and needs to learn Pythonic iteration.
Recommended by 12 people across 16 different months, 2013 to 2022.
Why Code Review Stack Exchange recommends it
Code Review Stack Exchange answerers link it when reviewing Python code that loops with manual index counters or Java-style iteration, as the standard guide to Pythonic looping.
Recommended by 4 people across 6 different months, 2016 to 2022.
What it is
Ned Batchelder's PyCon US 2013 talk on writing idiomatic Python loops. It covers while and for loops, iterators and generators, and why patterns like range(len(x)) are usually unnecessary, with examples such as turning nested loops into generators.
What people said
Strong rec Marwan Mostafa · 2019-06 · Stack Overflow · on “Difference between Python's Generators and Iterators”
Examples from Ned Batchelder [this video] highly recommended for iterators and generators A method without generators that do something to even numbers def evens(stream): them = [] for n in stream: if n % 2 == 0: them.append(n) return them while by using a generator def evens(stream): for n in stream: if n % 2 == 0: yield n We don't need any list nor a return statement Efficient for large/ infinite length stream ... it just walks and yield the value Calling the evens method (generator) is as usual num = [...] for n in evens(num): do_smth(n) Generator also used to Break double loop Iterator A book full of pages is an iterable , A bookmark is an iterator and this bookmark has nothing to do except t
Recommends JaminSore · 2013-08 · Stack Overflow · on “Scipy minimize, fmin, leastsq type problems (setting array element with sequence), bad fit”
No problem. To convert your function to a scalar, simple `return (result**2).sum()`. Also, `for i in range(len(x))` is almost always unnecessary as is looping over lists of numpy arrays. Your problem could probably be greatly simplified and sped up using numpy's broadcasting rules [LINK] . If you find you *have* to loop over lists of arrays, have a look at this video [this video] for a more Pythonic approach.
Recommends Back2Basics · 2013-11 · Stack Overflow · on “"Can only iterable" Python error”
An iterable is a thing with multiple items that you can iterate through (for example: take the 1st value do something, then the 2nd do something, etc...) Lists, dictionaries, tuples, strings have several items in them and can be used as iterables. As a counterexample: number types don't qualify as iterable. Remember that computers count from #0 so: if you want the first value of a list you can use my_list[0] before you go further I would suggest watching this video about looping. [this video]
Recommends SylvainD · 2016-01 · Code Review Stack Exchange · on “Game of Life search program for Herschel-generating baits”
Iterations The pythonic way to iterate is to use the for keyword, usually without bothering about indices. I suggest you have a look at the presentation : Ned Batchelder: Loop like a native: while, for, iterators, generators (PyCon US) ( video on Youtube [this video] / text with slides [LINK] ). In your case, most loops can be rewritten. For instance : n = 0 while n < testrect[2]: m = 0 while m < testrect[3]: o = 0 while o < len(stillLifes): testReaction(n + testrect[0], m + testrect[1], o) o += 1 m += 1 n += 1 could be written : for n in range(testrect[2]) for m in range(testrect[3]): for o, _ in enumerate(stillLifes): testReaction(n + testrect[0], m + testrect[1], o) Also, the for loop accepts
Recommends alexwlchan · 2016-10 · Code Review Stack Exchange · on “List of all prime factors of a number, including repeats”
Some general comments: Hooray for docstrings! It’s great that you’re writing these – it makes your code much easier to read and review, because I know what it’s supposed to do (and so can judge whether it does it correctly). And in general, these are pretty good docstrings. Do note that PEP 257 [LINK] says that one-line docstrings should end in a period. Don’t be stingy with variable names – characters are cheap, and if you write more descriptive names, the code becomes much easier to follow. For example, in generate_primes() , known_primes is better than l . There are a few minor PEP 8 [LINK] violations – in particular, space after comma in function arguments ( for i in range(1,n+1) ) and a
Recommends Back2Basics · 2016-11 · Stack Overflow · on “Python use command word in the function”
Command would be rewritten from this command = command[1:] command = command[:-1] command = command[15:] to this: command[16:-1] if you want to split up a string by a comma letter use: my_list = command.split(',') I think practicing with these 2 concepts will help you in your programming. (Python is not like C). Watch this for more looping details [this video]
Recommends Kevin J. Chase · 2017-03 · Stack Overflow · on “Using iter function inside next function”
`for index in range(len(anything)):` is a mistake most of the time --- Python will do all that busywork for you. Your loop could be as simple as `for char in string: print char`. See Ned Batchelder's " Loop Like a Native [LINK] " (30-minute video from PyCon US 2013 [this video] ) for easy ("Pythonic") ways to handle many cases like this.
Recommends diek · 2017-10 · Stack Overflow · on “string comparison for multiple values python”
Watch this, it will help a lot. Ned Batchelder - Loop like a native: while, for, iterators, generators [this video]
Recommends skrx · 2017-11 · Stack Overflow · on “Combining selected items from different lists into a new one”
You're welcome. BTW, I recommend watching Ned Batchelder's presentation "Loop like a native: while, for, iterators, generators" [this video] .
Recommends Post169 · 2018-03 · Stack Overflow · on “How can I break out of multiple loops?”
Yes, a speaker at a PyCon claims here [this video] that even @RobertRossney's accepted answer is not truly Pythonic, but a generator is the right way to break multiple loops. (I'd recommend watching the whole video!)