2

Could you tell me please, if I use for i in range(n), does python creates a range of 0 .. n-1, and iterates elements in this container (O(n) extra space), or it use only 1 vatiable (O(1)) space)

From one side, I thought, if we can convert range to list, then using range function creates a container (O(n)).but from the other side, instead of using for i in range(n), we can use while i < n ... O(1).

garrnizon
  • 31
  • 3

3 Answers3

3

In Python 3, range does not create all the elements, but only returns the current element when you request it. So yes, it's using O(1) space.

MadScience
  • 81
  • 2
  • I'm sure it has to store the context for the call, like start, step, end, and the last emitted value. But since those aren't proportional to the input, it's O(1) anyway. – Abhijit Sarkar Jun 30 '23 at 20:02
2

It's O(1): the range object doesn't store the values it yields.

As the Python documentation explains:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

Of course, if you make a list with the contents of the range, the list does use O(N) space.

slothrop
  • 3,218
  • 1
  • 18
  • 11
2

This was one of the big changes between Python 2 and Python 3. In Python 2, range created a full list, but you could avoid creating a list by instead using xrange. So in Python 2, you'd do for i in xrange(...) to efficiently iterate over a range without creating a temporary list.

In Python 3, this was changed so that range behaves like the Python 2 xrange. To get the Python 2 range behavior in Python 3, i.e. to create the full list, you can do list(range(...)), but of course you want to avoid that unless you truly need the list.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41