Chrome Extension

Python program to return multiple values from a function

To return multiple values from a function tuples can be used. The below program shows how to do it using tuples.
def my_function():
    value_1 = "devsheet"
    value_2 = 100
    value_3 = ["item 1", "item 2"]
    return value_1, value_2, value_3;

value_1, value_2, value_3 = my_function()
print(value_1)
print(value_2)
print(value_3)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
devsheet
100
['item 1', 'item 2']
def my_function():
    val_1 = "devsheet"
    val_2 = "hello world"
    return [val_1, val_2];  

items_list = my_function() 
print(items_list[0])
#-> "devsheet"

print(items_list[1])
#-> "hello world"
You can also use python list to return multiple values from a function. List are created using [] in python and you can add multiple values to it.In the above code snippet we are adding two values to the list and returning it from a function. After getting it, we are accessing them using list index.
def func():
  vals = {}
  vals['name'] = 'John'
  vals['address'] = 'New York'
  
  return vals
  
values = func()
print(values['name'])
# -> "John"

print(values['address'])
# -> "New York"
To return multiple values from a function, a python dictionary can also be used and you can add multiple key-value pairs to it and return them. You can access the values of a dictionary using its key names.
In the code snippets we are returning two values name and address using dict.
Was this helpful?
0 Comments
Join Devsheet Ask a Question