Pratyush Dhanuka
Pratyush Dhanuka

Reputation: 1445

difference between loop iterations in python and Java or C

I am learning python and seeing the difference in this loop conditions declarations I just have a question that how exactly the for loop in python is different from same algorithm for loopin C or Java, I know the difference in syntax but is there difference in the machine execution, and which is faster for example

for i in range(0,10):
    if i in range(3,7):
        print i

and in java

for(int i=0,i<10;i++){
    if i>=3 && i<7
        system.out.println(i);

Here I just want to know about the difference in actual iterations over 'i' not the printing statements or the output of the code.
Also comment on the if condition used to check whether 'i' is in between 3 and 7. in python if I had used the similar statement if i>=3 and i <7: what difference would have it made.

I am using python2.7

Upvotes: 2

Views: 2203

Answers (1)

salezica
salezica

Reputation: 77029

If you're using python 2.x, then the range call creates a full-fledged list in memory, holding all the numbers in the range. This would be like populating a LinkedList with the numbers in Java, and iterating over it.

If you want to avoid the list, there's xrange. It returns an iterable object that does not create the temporary list, and is equivalent to the Java code you posted.

Note that the in condition is not equivalent to a manual bounds check. Python will iterate through the range in O(n) looking for the item.

In python 3.x, xrange is no more, and range returns an iterable.

Upvotes: 3

Related Questions