[Python-ideas] More classical for-loop
Chris Angelico
rosuav at gmail.com
Fri Feb 17 12:40:07 EST 2017
On Sat, Feb 18, 2017 at 4:31 AM, Mikhail V <mikhailwas at gmail.com> wrote:
> I have said I need the index, probably you've misread my last comment.
> Further more I explained why I think iteration over index should be the
> preferred way, it help with readability a lot.
Further discussion probably should be redirected to python-list, but
I'll elaborate here to explain why I do not support your proposal.
You have a shelf of books. I ask you to go through the books and read
their titles out. How do you do it?
* Point your finger to the first book - probably the leftmost one, but
you might use some other order.
* Read out the title of that book.
* Point your finger to the next book.
* Read out that book's title.
* Continue until you reach the end of the shelf.
This corresponds to this code:
for book in books:
print(book.title)
Your style of iteration would be more like this:
* See how many books there are
* Locate the first book on the shelf
* Read out the title of book #1
* Locate the second book on the shelf
* Read out book title #2
* Continue until you've read as many titles as you originally counted books.
This is the code:
for i in range(len(books)):
print(books[i].title)
Which of these real-world algorithms is more natural?
The only reason the iteration counter feels more readable to you is
that you're accustomed to it. It's not an objective measure, it's an
entirely subjective one. That's not to say that it's unimportant for
that reason, but your line of argument must be "this feels more
comfortable TO ME", rather than "this is more readable".
Further elaboration on python-list, as mentioned above.
ChrisA
More information about the Python-ideas
mailing list