1

Imagine this code:

def code(n): 
    a = range(n) 
    b = list(a) 
    return b 

Am I correct to say that:

  • range(n) takes O(1) time (calling range in Python is constant time, right?)
  • list(a) takes O(n) time, and
  • The return statement takes O(1) time?
shripal mehta
  • 401
  • 4
  • 21
TWstud
  • 81
  • 6

1 Answers1

3

This is correct in Python 3; the range function returns a lazy iterable.

However, if you are using Python 2 then range(n) is also an O(n) operation, because it creates a list. range(n) in Python 2 is equivalent to list(range(n)) in Python 3.

The return statement takes O(1) time, because it only returns a reference to the list, not a copy of it.

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • In Python 2, `list(range(n))` should be a no-op, or not? – Jan Christoph Terasa Feb 24 '20 at 20:51
  • 1
    No; in Python 2 `range(n)` creates a list and then `list(...)` still makes a copy of it, so two lists are created (and the first one is garbage-collected). In theory `list` could be optimized so that if the argument is a list and its refcount is 1, then it can just return the argument directly; but I don't think that optimization is actually performed. – kaya3 Feb 24 '20 at 20:52
  • Ah, yes, of course. – Jan Christoph Terasa Feb 24 '20 at 20:52
  • @JanChristophTerasa almost never will you see that sort of optimization in CPython (maybe in something like PyPy). The best you can expect are things like constant folding, and sometimes, caching of objects that are used as literals in code and replacing them with immutable equivalents in the bytecode, e.g. `bad_word = word in {'foo', 'bar', 'baz'}` then the CPython compiler will make that a frozen set that is constructed once at compile time, but you really shouldn't rely on that, it is an implementation detail, and in any case, it is not a good practice from a clean code prespective – juanpa.arrivillaga Feb 24 '20 at 20:55