Is there a way I can return a list of lists without explicitly accessing the list by index? I would like to just return something like return *result. How can I do that in python?
def func():
result = [[1,2],[3,4]]
return result[0], result[1] # I want to return *result
print(func)
EDIT: I can't just return the result because I need to return each element, not the whole list as there are constraints. Also I wouldn't know how big the results are. so it could be up to return[100]
CodePudding user response:
return a tuple
:
def func():
result = [[1,2],[3,4]]
return tuple(result)
output: ([1, 2], [3, 4])
CodePudding user response:
This is not allowed in python. Python does now allow returning multiple things. The way python does it is by wrapping them in a tuple. For your example:
def func():
result = [[1,2],[3,4]]
return result[0], result[1]
def func2():
result = [[1,2],[3,4]]
return tuple(result)
print(type(func())) # prints tuple
print(type(func2())) # prints tuple
You can get the individual elements back by unwrapping the return value of the return value of the function call. Here is an example:
print(func()) # prints ([1, 2], [3, 4])
print(func2()) # prints ([1, 2], [3, 4])
print(*func()) # prints [1, 2] [3, 4]
print(*func2()) # prints [1, 2] [3, 4]
I would recommend to simply return the list as is. The only benefit I see for making it a tuple is that tuples are immutable, if that is something you need then return tuple(result)
.