Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python simple iteration

i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following 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

thanks very much

like image 840
nos Avatar asked Dec 14 '10 05:12

nos


People also ask

How do I make an iteration in Python?

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.

What is iteration in Python in simple words?

Repetitive execution of the same block of code over and over is referred to as iteration. There are two types of iteration: Definite iteration, in which the number of repetitions is specified explicitly in advance. Indefinite iteration, in which the code block executes until some condition is met.

What does __ ITER __ do in Python?

The __iter__() function returns an iterator for the given object (array, set, tuple, etc. or custom objects). It creates an object that can be accessed one element at a time using __next__() function, which generally comes in handy when dealing with loops.


2 Answers

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

like image 177
Karl Knechtel Avatar answered Sep 30 '22 16:09

Karl Knechtel


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

A bit of idiomatic Python: if you're trying to do something a set number of times with a range (with no need to use the counter), it's good practice to name the counter _. Example:

for _ in range(1000):
    # do something 1000 times
like image 42
Rafe Kettler Avatar answered Sep 30 '22 15:09

Rafe Kettler