python
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)
Output
devsheet
100
['item 1', 'item 2']
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.
In the code snippets we are returning two values name and address using dict.
Was this helpful?
Similar Posts
- [Python] Function returns multiple values
- # Python Program - Pattern Program 2
- [Python] Different ways to test multiple flags at once in Python
- # Python Program - Convert Hexadecimal to Binary
- Python program to convert a List to Set
- Python program to Generate a Random String
- Python - regex , replace multiple spaces with one space