Function that returns a tuple

Alex Martelli aleax at mac.com
Sun Jun 17 18:47:29 CEST 2007


David Wahler <dwahler at gmail.com> wrote:
   ...
> Tuples are immutable (can't be modified once created). Try this:
> 
> def BDllids():
>     conn = sqlite.connect('tasques.db')
>     cursor =  conn.cursor()
>     cursor.execute('SELECT * FROM tasques')
>     a = [row[0] for row in cursor]
>     return tuple(a)
> 
> Is there some particular reason you need to return a tuple as opposed to a
> list?

Assuming there is (need to use it as a dict key, RHS operand of string
formatting % operator, etc) I would suggest collapsing the last 2
statements in your excellent code into
  return tuple(row[0] for row in cursor)


> P.S. Accessing fields of a SELECT * by numeric index is prone to
> breakage if the order of your fields changes. You can make your code
> more robust by either specifying the column name explicitly in the
> SELECT statement. Alternatively, you may be interested in the

Absolutely true -- in this case, return tuple(cursor) will suffice.


Alex



More information about the Python-list mailing list