Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python function that returns a variable number of outputs

I want to input a table of unknown width (number of columns) and I want my function to output a list for each column. I am also outputting a list containing the names of the said lists.

I am trying this:

def crazy_fn(table):  
    titles=read_col_headers(table)  
    for i in range(1,len(table)):   
        for j in range(0,len(titles)):  
            vars()[titles[j]].append(table[i][j])  

    return titles, vars()[titles[k]] for k in range(0,len(titles))

The function works for when I know how many columns/lists I will output (return titles, a, b, c, d), but the way I've tried to generalize is not working.

like image 812
user1343236 Avatar asked Apr 19 '12 07:04

user1343236


People also ask

Can a function return a variable Python?

Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables. This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.

How do you write a function with variable number of arguments in Python?

The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-key worded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args.

How do you define a function that takes variable number of arguments?

In Python, there are two ways to define a function that can take a variable number of arguments. Different forms of this type are: Positional arguments. Keyword arguments.

What is the use of return How many values we can return in Python?

A function is not restricted to return a variable, it can return zero, one, two or more values. This is the default property of python to return multiple values/variables which is not available in many other programming languages like C++ or Java.


1 Answers

It's generally a bad idea to have a non-constant number of variables returned from a function, because using it is confusing and error-prone.

Why don't you return a dictionary mapping title headers to the list?

def crazy_fn(table):  
    result=dict()
    titles=read_col_headers(table)
    for title in titles:
        result[title]=VALUE(TITLE)
    return result

This can be abbreviated using dictionary comprehension to:

def crazy_fn(table):
   return {title : VALUE(TITLE) for title in read_col_headers(table)}
like image 88
Adam Matan Avatar answered Oct 05 '22 08:10

Adam Matan