Maiko Ohkawa Maiko Ohkawa - 20 days ago 7
Python Question

How can I get the number from iterator object. (Python2.7)

A method returns iterator object.
I want to check the number of data to test.

I think it is a simple question, but I coundn't resolve it.

records = a_function()
self.assertEqual(1, len(records)) # TypeError: object of type 'listiterator' has no len()


Python2.7

Answer

You need to convert the iterator to a list first:

len(list(records))

See:

>>> some_list = [1, 2, 3, 4, 5]
>>> it = iter(list)
>>> it = iter(some_list)
>>> len(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'list_iterator' has no len()
>>> len(list(it))
5
>>>

Note, however, that this will consume the iterator:

>>> list(it)
[]
>>>
Comments