What is the difference in these two lines of code in python?
for _ in range(i+1):
and
for _ in [0]*(i+1):
What is the difference in these two lines of code in python?
for _ in range(i+1):
and
for _ in [0]*(i+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.
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