Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for or while loop to do something n times

In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:

for i in range(n):     do_sth() 

And the other:

i = 0 while i < n:     do_sth()     i += 1 

My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

So what do you think, which way is better?

like image 516
Sventimir Avatar asked Jul 15 '13 06:07

Sventimir


People also ask

Should I use while or for loops?

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.

What type of loop would you use in these cases is no of times to loop is unknown initially?

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met.


1 Answers

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

like image 54
Amber Avatar answered Oct 04 '22 10:10

Amber