How to return multiple values in python
This tutorial is on How to return multiple values in python. we can return multiple values from a function. you can return multiple values by simply returning them separated by commas. As an example, define a function that returns a string and a number as follows. Here we are four-way to get multiple values:
- Object using
- Tuple using
- list using
- Dictionary using
Object using
We can create a class with multiple values and return an object of the class.
class useObject(object):
def __init__(self):
self.str = "Devnote"
self.num = 17
obj = useObject()
print(obj.str)
print(obj.num)
Output:
Devnote
17
Tuple using
A Tuple is a comma-separated sequence of items. It is created with or without ().
def tupalFun():
str = "Devnote"
num = 17
return str, num
str, num = tupalFun()
print(str)
print(num)
Output:
Devnote
17
list using
A list is like an array of items created using square brackets. Lists are different from tuples as they are mutable.
def listFun():
str = "Devnote"
num = 17
return [str, num]
list = listFun()
print(list)
Output:
['Devnote', 17]
Dictionary using
A Dictionary is similar to a hash or map in other languages.
def dictionaryFun():
dc = dict();
dc['str'] = "Devnote"
dc['num'] = 17
return dc
obj = dictionaryFun()
print(obj)
Output:
{'str': 'Devnote', 'num': 17}