On Tuesday, March 22, 2016 at 7:05:20 AM UTC-4, BartC wrote: > On 22/03/2016 01:01, Steven D'Aprano wrote: > > Pythonic code probably uses a lot of iterables: > > > > for value in something: > > ... > > > in preference to Pascal code written in Python: > > > > for index in range(len(something)): > > value = something[index] > > (Suppose you need both the value and its index in the loop? Then the > one-line for above won't work. For example, 'something' is [10,20,30] > and you want to print: > > 0: 10 > 1: 20 > 2: 30 )
Then you use enumerate: for index, value in enumerate(something): print("{}: {}".format(index, value)) Python has a number of iteration features that you don't find in other languages. You might find this introduction to them helpful: Loop Like a Native: http://nedbatchelder.com/text/iter.html > > > ... > > or worse: > > > > index = 0 > > while index < len(something): > > value = something[index] > > ... > > index += 1 > > > (I don't know where that while-loop idiom comes from. C? Assembly? Penitent > > monks living in hair shirts in the desert and flogging themselves with > > chains every single night to mortify the accursed flesh? But I'm seeing it > > a lot in code written by beginners. I presume somebody, or some book, is > > teaching it to them. "Learn Python The Hard Way" perhaps?) > > Are you suggesting 'while' is not needed? Not everything fits into a > for-loop you know! Steven wasn't saying 'while' is not needed. He was wondering about the idiom of manually maintaining an integer count of the number of times around a while loop ("I don't know where *that* while-loop idiom comes from"). While-loops are still useful in Python, but for-loops are much more common. --Ned. -- https://mail.python.org/mailman/listinfo/python-list