I am trying to count the output in python. len seems to be not working with the output. Following is my code
for i in range(0, 5):
print i
The output is
0
1
2
3
4
I want to print the count of i which should give me 5
Use enumerate to count the iterations:
count = 0 # In case loop is empty
for count, i in enumerate(range(5), 1):
print(i)
print(count)
If you want the size of a list use len:
print(len(range(5)))
count = 0 before the loop, it even works with an empty loop, such as range(0, 0).There are many ways to do it but my two ways would be:
Use len
i = len(range(0, 5))
print i
Use for:
j = 0
for i in range(0, 5):
# Other things you want to do
j += 1
print j