6

We can do numeric iteration like:

for i in xrange(10):
    print i,

and in C-style:

i = 0
while i < 10:
    print i,
    i = i + 1

Yes, I know, the first one is less error-prone, more pythonic but is it fast enough as C-style version?

PS. I'm from C++ planet and pretty new on Python one.

5
  • 6
    Why not strive for simplicity and clarity? Why fuss over micro-optimizations?
    – S.Lott
    Sep 4, 2009 at 10:01
  • I thought xrange was being deprecated.
    – Jon W
    Sep 4, 2009 at 15:47
  • 2
    Jweede: No xrange is renamed to range in Python 3.0 (all list-returning methods are replaced like that ("deprecated"), for example filter, map and dict.keys()) Sep 4, 2009 at 15:59
  • 4
    Fastest is print "0 1 2 3 4 5 6 7 8 9"
    – flybywire
    Nov 16, 2009 at 8:07
  • 1
    "I am interested in doing X" - inquisitive SO poster. "You shouldn't be, instead be interested in Y" - unhelpful SO response. Nov 20, 2017 at 23:11

7 Answers 7

17

I am sure the while version is slower. Python will have to lookup the add operation for the integer object on each turn of the loop etc, it is not pure C just because it looks like it!

And if you want a pythonic version of exactly the above, use:

print " ".join(str(i) for i in xrange(10))

Edit: My timings look like this. This is just a silly running loop without printing, just to show you what writing out "i += 1" etc costs in Python.

$ python -mtimeit "i=0" "while i < 1000: i+=1"
1000 loops, best of 3: 303 usec per loop
$ python -mtimeit "for i in xrange(1000): pass"
10000 loops, best of 3: 120 usec per loop
5
  • 5
    in Python 3, where print is a function, just say print(*range(10)) Sep 4, 2009 at 9:29
  • 2
    @kaizer.se: you can do so in python 2.6 with from __future__ import print_function
    – nosklo
    Sep 4, 2009 at 11:23
  • nosklo: right you are. I use python2.5. (I'm sure the excercises in my answer are pointless, but Edwards asked how to do it in a comment to Roberto Liffredo's answer.) Sep 4, 2009 at 11:25
  • Thanks a lot! "Python will have to lookup the add operation for the integer object on each turn of the loop etc" - this is exactly that I don't know: how it works. Could you recommend some good source about Python internals?
    – bocco
    Sep 7, 2009 at 19:24
  • bocco: There must be a stackoverflow question already asked that can answer that much better than I. The official docs are to recommend, you can read into any area there docs.python.org Sep 7, 2009 at 19:33
15

Who cares? Seriously. If you want to know, use timeit package (you can invoke it from command line with -m).

But it doesn't matter at all, because the difference is negligible. And in general, Python is not a language that you choose if you want speed.

3
  • 3
    Yes, and in all likelihood, each Python implemenattion could do this differently. Trust the compiler. I recall the time when C code SHOULD use "do-while" or "while" to be faster... according to what happened on some old broken compiler ten years ago. This sounds like the same kind of thinking. Sep 4, 2009 at 6:00
  • 1
    Python offers speed not if you optimize your loops but if you think about your algorithms and data structures, which may be easier to adapt than in C. Sep 4, 2009 at 9:31
  • True for Python is not a language for speed. I implemented a game AI algorithm in Python and found it 10x slower than same code written in JavaScript, let alone C.
    – iBug
    May 19, 2018 at 6:07
3

The first one.

You mean, faster to develop, right?

PS: It doesn't matter, machines these days are so fast that it is meaningless to ponder on micro optimizations, prior to identifying the bottlenecks using a thorough profiler.

2
  • 4
    That's simply not true.
    – roim
    Oct 9, 2015 at 18:18
  • It matters a lot for some cases.
    – hopflink
    Oct 1, 2018 at 1:42
2

They are both to avoid :-)

Generally speaking, each time I see an iteration over numbers, I see some non-pythonic code, that could be expressed in a better way using iterations over lists or generators.
Actually, I've said "pythonic", but it is all about readability. Using idiomatic code will increase readability, and ultimately also performance, because the compiler will better know how to optimize it.

4
  • 1
    Roberto it woudl help beginner python programmers if you show us how you would do teh above in a pythonic way
    – Edwards
    Sep 4, 2009 at 8:39
  • +1 Very true, although it's not a direct answer to the question. Also, you usually iterate over some list or the like and just need the numbers as additional information---and that's what enumerate() is for.
    – balpha
    Sep 4, 2009 at 9:50
  • 5
    The code snippet doesn't have enough context. But the classic mistake is for i in xrange(len(A)): a[i]... that's just wrong.
    – S.Lott
    Sep 4, 2009 at 10:33
  • 2
    @Edwards: as Steven said, there's not enough context to give a "pythonic" version of the code. Usually, you should try not to think in terms of indexes, but of data structures (lists, dictionaries, etc). Once you've done that shift, everything's much easier.
    – rob
    Sep 4, 2009 at 19:18
1

If your program is too slow, try using psyco.

Don't worry about the kind of micro-optimisation in your question. Write your program to be maintainable (which includes following standard Python style so other programmers can read it easier).

0

In Python, the shorter and clearer version is always better. If I am not mistaken the range and xrange functions are not native, if you try xrange(sys.maxint+1) you will get an overflow error.

Besides, what the hell could this be useful for? If you are just printing 10 numbers, then surely readability counts a thousand times more - and I don't think you're going to print over a million numbers...

0

Well, if you are after efficiency in numerical code, you ought to use numpy and scipy. Your integration can be quickly written as numpy.sum( numpy.arange( 10 ) )

1
  • Sum of a range of integers should be done as 10 * (10+1) / 2, not with a loop. See also kristerw.blogspot.com/2019/04/… for how C compilers (or clang specifically) optimizes sums of i^2 or i to any power. github.com/llvm/llvm-project/blob/… cites some references for formulae and algorithms they use. But a simple sum of consecutive integers is just Gauss's famous n * (n+1)/2 in Python where overflow is impossible. Can be adjusted for gaps like sum(2*i). Dec 25, 2022 at 3:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.