__nonzero__ of iterators

Jack Diederich jack at performancedrivers.com
Thu Apr 1 23:50:19 EST 2004


On Thu, Apr 01, 2004 at 10:30:10AM +0200, Christian Eder wrote:
> Hi,
> 
> I just discovered the following pitfall in Python 2.3.
> Consider the following code :
> 
> >>> a = {}
> >>> bool (a.keys ())
> False
> >>> bool (a.iterkeys ())
> True
> 

>>> a = {}
>>> a.keys()
[]
>>> a.iterkeys()
<dictionary-iterator object at 0x401973c8>
>>> list(a.iterkeys())
[]

a.iterkeys() is returning an iterator.
list(a.iterkeys()) is returning all of the elements in the iterator (empty)

If you want to test the boolean just use
if (a):
  blah = 1

-jackdied




More information about the Python-list mailing list