1

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Which version of Python? Does `value, *_ = ...` work? Also I wouldn't count 0 as a magic number in this case. – jonrsharpe Feb 13 '17 at 13:57

2 Answers2

6

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).

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

By accessing the element using its index would be easier, hope it helps, I explained this using a very basic example :

def test_function():

return 1,3,4,5,6

#--- Getting function output using index ----#

print('',f()[0],' \n',f()[1],'\n',f()[2],' ..........')

result:

 1  
 3 
 4  ..........
Ikbel
  • 1,817
  • 1
  • 17
  • 30