Trygve Aspenes Trygve Aspenes - 6 months ago 14
Python Question

lenght of a list of elementtree turn 0 after second call

I have a code like this

import xml.etree.ElementTree as etree
tree = etree.fromstring("<all_products><product instrument_name='nice_instrument'></product></all_products>")
product_iter = tree.iterfind("product[@instrument_name='nice_instrument']")
len(list(product_iter))


And this gives me len of the list of product_iter 1 as expected.

But if a call the len(list(product_iter)) again I get 0.

I dont understand why this happens. Can someone explain why the product_iter variable is somehow changed whan a call the len to the list?

Looking at the documentation for elementtree https://docs.python.org/2/library/xml.etree.elementtree.html I dont see any information how to explain this.

Regards
Trygve

Answer

product_iter is an iterator, not a list. If you convert it to a list, the len will stay 1:

>>> import xml.etree.ElementTree as etree
>>> tree = etree.fromstring("<all_products><product instrument_name='nice_instrument'></product></all_products>")
>>> product_iter = tree.iterfind("product[@instrument_name='nice_instrument']")
>>> products = list(product_iter)
>>> len(products)
1
>>> len(products)
1