EDIT 3: The answer from @hynekcer is much better than this.
EDIT 2: This will not work if you have an infinite iterator, or one that consumes too many gigabytes (in 2010 1 gigabyte still remains a large amount of RAM / disk space) of RAM / disk space.
You have already seen a good answer, but here is an expensive hack that you can use if you want to eat a cake, and you too :) The trick is that we should clone the cake, and when you are done we will return it to the same box. Remember that when you iterate over an iterator, it usually becomes empty or at least loses the previously returned values.
>>> def getIterLength(iterator): temp = list(iterator) result = len(temp) iterator = iter(temp) return result >>> >>> f = xrange(20) >>> f xrange(20) >>> >>> x = getIterLength(f) >>> x 20 >>> f xrange(20) >>>
EDIT: Here is a safer version, but using it still requires some discipline. It does not feel pretty pythonic. You would get a better solution if you posted all the relevant code sample that you are trying to implement.
>>> def getIterLenAndIter(iterator): temp = list(iterator) return len(temp), iter(temp) >>> f = iter([1,2,3,7,8,9]) >>> f <listiterator object at 0x02782890> >>> l, f = getIterLenAndIter(f) >>> >>> l 6 >>> f <listiterator object at 0x02782610> >>>
Hamish grubijan
source share