[Tutor] for loops when there is only one row in the result - is there an alternative?
Steven D'Aprano
steve at pearwood.info
Fri Nov 26 03:55:51 CET 2010
Rance Hall wrote:
> Generally you have something like this:
>
> clientlist = get_clients() # where get_clients is a prepared sql statement.
>
> normally you would get the individual rows like this:
>
> for row in clientlist:
> do stuff
>
>
> which is great for a long list of results. But I'm running into
> issues when there are only 0 or 1 results in the set.
If clientlist is empty, you don't need to explicitly test for it:
>>> clientlist = [] # nothing there
>>> for row in clientlist:
... print("Hello world")
...
>>>
Notice that nothing gets printed.
> if there are zero rows then I can do something like:
>
> if len(clientlist) == 0:
> do stuff
Generally one merely needs to check the list itself:
if clientlist:
...
although be warned that "lazy lists", or iterators, are slightly
different -- but if len(clientlist) works, then this should also work.
> I'm looking for a better way to access the row when there is just one
> row in the result.
This should work:
row, = clientlist # if one row only -- note the comma!
row1, row2 = clientlist # if two rows
row1, row2, row3 = clientlist # three rows
If the comma in the first example is too subtle, try this:
[row] = clientlist
Another way which should work:
row = clientlist[0]
> Say from a user login attempt, or a request to edit an existing client record.
>
> Is there a decent way to get direct access to the single row in the
> result set without having to go through the for loop for just one
> item?
>
> It likely helps to know exactly what variable type clientlist would
> be. I have no idea.
type(clientlist) will tell you.
--
Steven
More information about the Tutor
mailing list