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

1
  • There is no question in your post. What do you mean with number of data? Commented Nov 15, 2016 at 6:45

2 Answers 2

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

1 Comment

Thank you. It worked fine. Yes, records is iterator object, this name is not suitable, I think. Thank you everyone.
2

You can easily do it by

sum(1 for _ in it)

where it is the iterator you want to find length.

2 Comments

That's a bit cheeky: dupe flagging and then posting an answer. But I'll let you get away with it this time. ;)
;). Wont repeat again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.