Python simple iteration

I would like to ask what is the best way to do a simple iteration. Suppose I want to repeat a specific task 1000 times, which one is the best? or is there a better way?

for i in range(1000): do something with no reference to i i = 0 while i < 1000: do something with no reference to i i += 1 

Thank you very much

+4
source share
4 answers

The first is considered idiomatic. In Python 2.x, use xrange instead of range .

+4
source

The for loop is shorter and more readable. while loops are rarely used in Python (with the exception of while True ).

A little idiomatic Python: if you are trying to do something a certain number of times with a range (without having to use a counter), it is recommended to use the counter _ . Example:

 for _ in range(1000): # do something 1000 times 
+4
source

In Python 2 use

 for i in xrange(1000): pass 

In Python 3 use

 for i in range(1000): pass 

Performance metrics for Python 2.6:

 $ python -s -m timeit '' 'i = 0 > while i < 1000: > i += 1' 10000 loops, best of 3: 71.1 usec per loop $ python -s -m timeit '' 'for i in range(1000): pass' 10000 loops, best of 3: 28.8 usec per loop $ python -s -m timeit '' 'for i in xrange(1000): pass' 10000 loops, best of 3: 21.9 usec per loop 

xrange preferable to range in this case, because it generates a generator, and not the entire list [0, 1, 2, ..., 998, 999] . He will use less memory. If you need an actual list to work with everyone right away, this is when you use range . Usually you want xrange : why in Python 3, xrange(...) becomes range(...) and range(...) becomes list(range(...)) .

+4
source

first. because the whole is executed in the inner layer, and not in the interpreter. Also one less global variable.

0
source

Source: https://habr.com/ru/post/1332069/


All Articles