I often see code like:
Iterator i = list.iterator(); while(i.hasNext()) { ... }
but I write that (when Java 1.5 isn't available or for each can't be used) as:
for(Iterator i = list.iterator(); i.hasNext(); ) { ... }
because
i
in a smaller scopei
used outside the while? Where is i
declared?)I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: http://jamesjava.blogspot.com/2006/04/iterating.html
Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.
The “while” loopA single execution of the loop body is called an iteration. The loop in the example above makes three iterations. If i++ was missing from the example above, the loop would repeat (in theory) forever.
in general a while loop is used if you want an action to repeat itself until a certain condition is met i.e. if statement. An for loop is used when you want to iterate through an object.
Answer: yes, for loop is more pythonic choice.
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With