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 Variables, Constants and Literals
Python help()
Python locals()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python String upper()
Python Program to Find the Factors of a Number
Python List count()
Python String istitle()
Python Program to Find Factorial of Number Using Recursion
Python Statement, Indentation and Comments
Python input()
Python object()
Python Strings
Python Program to Find All File with .txt Extension Present Inside a Directory
Python String index()
Python getattr()
Python Keywords and Identifiers
Python Shallow Copy and Deep Copy
Python range()
Python Multiple Inheritance
How to Get Started With Python?
Python time Module
Python File I/O Operation
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Sort a Dictionary by Value
Python reversed()
Python Program to Find the Factorial of a Number
Python hex()
Python Tuple index()
Python Operator Overloading
Python del Statement
Debug a JavaMail Program