for
is pretty much the "default" choice in Python when you want to iterate a definite number of times. For example:
for i in xrange(10):
#do stuff
#iterates 10 times
for an_element in a_collection:
#do stuff
#iterates over every element in a collection
#though generators can be "infinite"
However, if you want to loop over code an indefinite number of times, a while
loop is more idiomatic.
while a_boolean:
#do stuff
#iterates as long as a_boolean evaluates to True
while True:
#do stuff
#iterates till a break is encountered
Since you come from a Java background, a while
loop in Python is pretty much the same as a while
loop in Java and is used in much the same way. A for
loop in Python is like:
for(Integer i : anArrayListOfIntegers){
//do stuff
}
The for(int i=0;i<10;i++)
form doesn't exist in Python, you use the range()/xrange()
form in the first example instead. That said, every for
loop can be replaced with an equivalent while
loop except in the case of list comprehensions/generator expressions and the like.
There are no real advantages or disadvantages to doing this in terms of speed or memory usage. However, Python programmers tend to use for
when they are iterating over collections and while
when they want to iterate while or until a condition is true. If you stick to this general rule of thumb, you probably won't go wrong.