I have a function where I need to return 2 lists that are created inside the function in python 3.x. Rather than returning the lists I can rather take the 2 lists as arguments and append whatever info I need in those lists. My other approach would be to return a dictionary with the 2 lists and then get the lists my using the key after the function returns. Both these methods require preparation before/after the function call, so I'm just wondering if there is a better way of returning the lists, and if not which of these 2 approaches are better.
Example code:
def method1(list1, list2):
*do something to lists*
def method2():
*do something to lists*
return({'list1': list1, 'list2': list2})
get_lists_method1():
list1 = []
list2 = []
method1()
get_lists_method2():
list_dict = method1()
list1 = list_dict['list1']
list2 = list_dict['list2']
Edit, method using tuples:
def method3():
*create and do something with lists*
return (list1, list2)
get_lists_method3():
list1, list2 = method3()
I would use tuple assignment. Since the two return values go together, just return (list1, list2)
# returns a tuple of two lists
def method1(list1, list2):
list1.append(4)
list2.append(8)
return (list1, list2)
# the lists are result[0] and result[1]
result = method1([1, 2, 3], [2, 4, 6])
for l in result:
print l
# more useful: tuple assignment
(list1, list2) = method1([1, 2, 3], [2, 4, 6])
print list1
print list2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments