2

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

Maiko Ohkawa
  • 853
  • 2
  • 11
  • 28

2 Answers2

11

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)
[]
>>>
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • Thank you. It worked fine. Yes, `records` is iterator object, this name is not suitable, I think. Thank you everyone. – Maiko Ohkawa Nov 15 '16 at 06:55
2

You can easily do it by

sum(1 for _ in it)

where it is the iterator you want to find length.

Stormvirux
  • 879
  • 3
  • 17
  • 34