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 Set issubset()
Python String isprintable()
Python Modules
Python Program to Append to a File
Python Program to Print all Prime Numbers in an Interval
Python String isupper()
Python Program to Randomly Select an Element From the List
Python Program to Generate a Random Number
Python Program to Find Sum of Natural Numbers Using Recursion
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python List Comprehension
Deep Learning with Python - Francois Chollet
Python isinstance()
Python sum()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Convert String to Datetime
Python format()
Python strftime()
Python Program to Capitalize the First Character of a String
Python Set intersection_update()
Python Program to Get File Creation and Modification Date
Python exec()
Python File I/O Operation
Python zip()
Python Dictionary
Python Function Arguments
Python List insert()
Python Program to Find HCF or GCD
Python Program to Remove Duplicate Element From a List
Node.js vs Python for Backend Development
Python Program to Measure the Elapsed Time in Python
Python Program to Display Powers of 2 Using Anonymous Function