0

I have a function F() that returns two objects. E.g. ob1, ob2 = F().

Is there a way to just access ob1 and ignoring ob2 in the same line? something like ob1 = F().

Jack Twain
  • 6,273
  • 15
  • 67
  • 107

3 Answers3

2

Just follow the naming convention for throwaway variables:

ob1, _ = F()

Another option is to get the first item from the result of F():

obj1 = F()[0]
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

Functions can never return two objects at once. Instead, your function is returning a tuple that contains two objects.

This means that you can use indexing to get the object you want:

>>> def F():
...     return 1, 2
...
>>> ob1 = F()[0]
>>> ob1
1
>>>

Remember that it is the comma , that creates a tuple, not the parenthesis (if any):

>>> t = 1, 2
>>> t
(1, 2)
>>> t = (1, 2)
>>> t
(1, 2)
>>>
0

As the result will be a tuple, just access the position you need:

ob1 = F()[0]
Joël
  • 2,723
  • 18
  • 36