Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values from *args?

I have a hello function and it takes n arguments (see below code).

def hello(*args):
  # return values

I want to return multiple values from *args. How to do it? For example:

d, e, f = hello(a, b, c)

SOLUTION:

def hello(*args):
  values = {} # values
  rst = [] # result
  for arg in args:
    rst.append(values[arg])
  return rst

a, b, c = hello('d', 'e', f)
a, b = hello('d', 'f')

Just return list. :) :D

like image 529
Zeck Avatar asked Dec 05 '11 06:12

Zeck


2 Answers

So, you want to return a new tuple with the same length as args (i.e. len(args)), and whose values are computed from args[0], args[1], etc. Note that you can't modify 'args' directly, e.g. you can't assign args[0] = xxx, that's illegal and will raise a TypeError: 'tuple' object does not support item assignment. What You need to do then is return a new tuple whose length is the same as len(args). For example, if you want your function to add one to every argument, you can do it like this:

def plus_one(*args):
    return tuple(arg + 1 for arg in args)

Or in a more verbose way:

def plus_one(*args):
    result = []
    for arg in args: result.append(arg + 1)
    return tuple(result)

Then, doing :

d, e, f = plus_one(1, 2, 3)

will return a 3-element tuple whose values are 2, 3 and 4.

The function works with any number of arguments.

like image 102
Johan Boulé Avatar answered Oct 05 '22 12:10

Johan Boulé


Just return a tuple:

def hello(*args):
    return 1, 2, 3

...or...

    return (1, 2, 3)
like image 27
detly Avatar answered Oct 05 '22 12:10

detly