Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return two lists from a function in python

I am new to python programming and need your help for the following:

I want to return two lists from a function in python. How can i do that. And how to read them in the main program. Examples and illustrations would be very helpful.

Thanks in advance.

like image 952
heretolearn Avatar asked Jul 27 '12 14:07

heretolearn


People also ask

Can you return 2 lists in Python function?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

How do I return multiple lists from a function in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.

Can you have 2 returns in a function?

You can't return two values. However, you can return a single value that is a struct that contains two values. Show activity on this post. You can return only one thing from a function.

Can a function return multiple arrays Python?

You can only return once from a method. However, the data can still be accessed on separate lines.


2 Answers

You can return a tuple of lists, an use sequence unpacking to assign them to two different names when calling the function:

def f():     return [1, 2, 3], ["a", "b", "c"]  list1, list2 = f() 
like image 84
Sven Marnach Avatar answered Oct 05 '22 22:10

Sven Marnach


You can return as many value as you want by separating the values by commas:

def return_values():     # your code     return value1, value2 

You can even wrap them in parenthesis as follows:

return (value1, value2) 

In order to call the function you can use one of the following alternatives:

value1, value2 = return_values() #in the case where you return 2 values  values= return_values() # in the case values will contain a tuple 
like image 22
Stefano Avatar answered Oct 06 '22 00:10

Stefano