2

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

0

2 Answers 2

3

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

If you do count = 0 before the loop, it even works with an empty loop, such as range(0, 0).
1

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

2 Comments

Thank you very much, this is exactly what I am looking for. :)
@Srivamsi happy to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.