Maiko Ohkawa Maiko Ohkawa - 1 year ago 106
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()


Answer Source

You need to convert the iterator to a list first:



>>> 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))

Note, however, that this will consume the iterator:

>>> list(it)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download