2

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

6
  • 1
    Python2.x or Python3.x? Commented Mar 28, 2014 at 7:43
  • I think a bounds check is actually faster than seeing if it is in a range? Someone correct me if I'm wrong... Commented Mar 28, 2014 at 7:44
  • You could easily time this by yourself. It would be interesting. Commented Mar 28, 2014 at 7:45
  • @uʍopǝpısdn then both should result in the same performance i mean the bounds vs range. Commented Mar 28, 2014 at 7:46
  • When posting code here, please try to make sure it's valid code. If you're posting pseudo-code, then state so. Commented Mar 28, 2014 at 7:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tested range(5,10) and xrange(5,10) in python and understood what you meant. damm i have been using range only all this time
It's not really a problem for small ranges :)
Yes but I have been using python for a MOCC on Discrete Optimization and for assignments we have to solve problems like knapsack in python where the test cases includes data up 10000s nodes. Also i stopped using in where I dont really have to

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.