L
L
leham12021-06-22 15:01:21
Python
leham1, 2021-06-22 15:01:21

How to find out the length of an iterator?

To find out the length of a list, use len(). But len() does not work when I make an iterator from the list using iter().
Is there any way to find out the length of an iterator? If so, how?

a = [1,2,3,4]
print(len(a))
a2 = iter(a)
print(len(a2))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2021-06-22
@leham1

No, iterators are unlimited.

A
alfss, 2021-06-22
@alfss

a = [1,2,3,4]
print(len(a))
a2 = iter(a)
print(len(list(a2)))

a = [1,2,3,4]
print(len(a))
a2 = iter(a)
print(sum(1 for _ in a2))

M
MinTnt, 2021-06-25
@MinTnt

The maximum that is possible is just to turn it into an object of a different type, which has the ability to len ().
print(len([*a2]))
Well, iterators do not have methods to get its length.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question