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.
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.
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.
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.
You can only return once from a method. However, the data can still be accessed on separate lines.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With