In this example, you will learn to return multiple values from a function.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Return values using comma
def name():
return "John","Armin"
# print the tuple with the returned values
print(name())
# get the individual items
name_1, name_2 = name()
print(name_1, name_2)
Output
('John', 'Armin')
John Armin
When you return multiple values using comma(s), they are returned in the form of a tuple. As shown in the code above, two strings "John" and "Armin" are returned with a single return statement.
2. Example 2: Using a dictionary
def name():
n1 = "John"
n2 = "Armin"
return {1:n1, 2:n2}
names = name()
print(names)
Output
{1: 'John', 2: 'Armin'}
When you return values using a dictionary, it is easy for you to keep track of the returned values using the keys. The return statement returns the two variables in the form a dictionary.
Related posts:
Python Program to Get the Full Path of the Current Working Directory
Python List remove()
Python enumerate()
Python Set isdisjoint()
Python String isidentifier()
Python Matrices and NumPy Arrays
Python Dictionary pop()
Python String rfind()
Python Program to Differentiate Between del, remove, and pop on a List
Python Custom Exceptions
Python Tuple count()
Python Operator Overloading
Python Anonymous / Lambda Function
Python bytearray()
Java Program to Implement the Program Used in grep/egrep/fgrep
Python property()
Python Program to Delete an Element From a Dictionary
Python Program to Check Prime Number
Python Program to Slice Lists
Python Global Keyword
Python int()
Python Program to Check Armstrong Number
Python Numbers, Type Conversion and Mathematics
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Check If a String Is a Number (Float)
Python List reverse()
Python Objects and Classes
Python bytes()
Python String upper()
Python String isprintable()
Python Set copy()
Python Program to Iterate Over Dictionaries Using for Loop