There is a function

def summa_and_raznost(a, b): summa = a + b raznost = b - a return summa, raznost 

Is it possible to call a function so that not all values ​​are received, but as many as necessary, without creating a tuple with parentheses, a set or a list that needs to be parsed? for example

 summa, raznost = summa_and_raznost(2, 3) # return 5, 1 

and

 summa = summa_and_raznost(2, 3) # return 5 

If it is impossible, then how to do it differently?

  • four
    my_sum, _ = sum_and_dif(2, 3) PS never use the names of built-in functions, types or reserved words as variable names - sum() - built-in function - MaxU
  • for reference, the name of the function sum_and_dif does not "intersect" with the built-in ones, so it can be safely used ... - MaxU

1 answer 1

As an example, we can take the function divmod (a, b) , which returns a tuple consisting of the result of an integer division, a // b and the remainder of the division, a % b :

 res, mod = divmod(17,3) print(res, mod) >>> 5 2 

there is an agreement to use a single or double underscore as the name of an "unnecessary" variable (which we are not going to use) :

 res, __ = divmod(17, 3) print(res) >>> 5 

The variable __ is also available:

 print(__) >>> 2 

You can also select the desired element of the tuple ( as suggested in the @Alex Titov comments ) - and the memory should be freed faster:

 res = divmod(17, 3)[0] print(res) >>> 5 
  • And so that it is not transmitted at all? - Elefanobi
  • @Elefanobi, the function is responsible for the transfer, but it is not aware of the context in which you call it. You can create another function. - vp_arth
  • 3
    By the way, the “philosophical” question :) what is better for 2 parameters - res, _ = divmod(17,3) , or res=divmod(17,3)[0] ? - Alex Titov
  • one
    @AlexTitov, good question! Probably your option is better, because memory does not clog ... - MaxU
  • one
    @vp_arth, to be honest, the option with [False] depresses me much more - I have to think what the author wanted to say ... - MaxU