Help with generators outside of loops.

Steven Bethard steven.bethard at gmail.com
Tue Dec 7 22:53:37 EST 2004


Robert Brewer wrote:
> Christopher J. Bottaro wrote:
> 
>>I have a generator that works like this:
>>
>>for row in obj.ExecSQLQuery(sql, args):
>>        # process the row
>>
>>Now there are some querys that run where I know the result 
>>will only be a
>>single row.  Is there anyway to get that single row from the generator
>>without having to use it in a for loop?  I want to do 
>>something like this:
>>
>>row = obj.ExecSQLQuery(sql, args)[0]
>>
>>But I'm guessing that you can't index into a generator as if 
>>it is a list.
> 
> 
> row = obj.ExecSQLQuery(sql, args).next()

I don't do much with SQL/databases stuff, but if you really know the 
result will be a single row, you can take advantage of tuple unpacking 
and do something like:

row, = obj.ExecSQLQuery(sql, args)

or

[row] = obj.ExecSQLQuery(sql, args)

This has the advantage that you'll get a ValueError if you happen to be 
wrong (and there are more or fewer values in the generator).

 >>> def g(n):
...     for i in range(n):
...         yield i
...
 >>> x, = g(1)
 >>> x
0
 >>> x, = g(2)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
ValueError: too many values to unpack
 >>> x, = g(0)
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
ValueError: need more than 0 values to unpack

Steve



More information about the Python-list mailing list