I'm working with kinterbasdb module, and the module has this function called fetchone, that returns the result of an execution of a query:
cursor.execute("....")
cursor.fetchone()
This returns a tuple: ("value1",)
, and i want access the first item, but avoiding the [0]
in the end, since doesn't tell much, it's a magic number. Is it possible? Perhaps some build in function?
I was trying to with:
value, _ = cursor.fetchone()
But this is returning: ValueError: need more than 1 value to unpack
, since the index 1 doesn't have anything.
The problem with:
value, _ = cursor.fetchone()
# ^ a variable with identifier _
is that it here expects two elements in the tuple you wish to unpack, but the tuple contains only one element. You can however solve this by writing a comma, but no variable like:
value, = cursor.fetchone()
# ^ no variable
mind that you have to write the comma ,
: omitting it will not unpack the tuple.
or in case the number of elements in the tuple is unknown (but larger than zero), you could use the aterisk:
value, *_ = cursor.fetchone()
which will unpack the remaining elements in a tuple _
. In case the expression has a tuple with one element, _
will be equal to _ == ()
(the tuple with no elements). In case you unpack for instance (1,4,2,5)
, it will result in value == 1
and _ == (4,2,5)
.