2

What is the difference in these two lines of code in python?

for _ in range(i+1):

and

for _ in [0]*(i+1):
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Junth
  • 27
  • 6
  • Side-note: `range` is generally considered the idiomatic way to run a loop `n` times while ignoring the iteration value, but if you're trying to squeeze out every last drop of speed, you can do a little better by using `for _ in itertools.repeat(None, i + 1):`, which, like Py3 `range`, behaves as a virtual iterator in this context (values produced on demand, no large temporaries precomputed as in `[0]*(i+1)`), but in addition, doesn't produce any per iteration objects at all (`range` must make brand new `int`s beyond an implementation detail boundary). – ShadowRanger May 03 '18 at 12:56
  • Closely related: [Is it possible to implement a Python for range loop without an iterator variable?](https://stackoverflow.com/q/818828/364696) given that these code snippets are both attempts to perform the task requested in that question. – ShadowRanger May 03 '18 at 13:02

2 Answers2

1

range(i+1) creates an object of class range while [0]*(i+1) creates a list of i+1 elements. range object will generate an iteration of i+1 elements, but does not occupy memory space for them.

Using _ variable on above range will generate items from 0 to i, while the second code block generates a list of 0 values only.

Konrad Talik
  • 912
  • 8
  • 22
0

The first line will create a range object and the second a list object. For example

>>> i = 5
>>> print(range(i+1))
range(0, 6)
>>> print([0]*(i+1))
[0, 0, 0, 0, 0, 0]

and iterating through them produces

>>> for _ in range(i+1):
...     print(_)
...
0
1
2
3
4
5
>>> for _ in [0]*(i+1):
...     print(_)
...
0
0
0
0
0
0
haklir
  • 76
  • 4