In Python, we can return multiple values from a function through various methods. The following article will introduce to you how to return multiple values from a function. I hope it will be helpful to you.
Method One: Using Object
This is similar to C/C and Java, we can create A class to hold multiple values and return an object of that class.
Let’s use a code example to see how to return multiple values in a function
class Test: def __init__(self): self.str = "hello world!" self.x = 20 # 返回一个对象 def fun(): return Test() t = fun() print(t.str) print(t.x)
Output:
hello world! 20
Method 2: Use List
In Python, lists are like arrays of items created using square brackets, they are mutable. They differ from arrays in that they can contain items of different types.
Let’s take a look at the code example to see how to return multiple values in a function
# 返回一个列表 def fun(): str = "hello" x = 20 return [str, x]; list = fun() print(list)
Output:
['hello', 20]
Method 3: Use Tuple
In Python, a tuple is a comma-separated sequence of items; it is a sequence of immutable Python objects. Tuples are similar to lists, except that once declared, a tuple cannot be changed (tuples are immutable). Tuples are generally faster than lists.
The following is a code example to see how to return multiple values in a function
# 返回一个元组 def fun(): str = "你好!" x = 2019 return str, x; str, x = fun() # Assign returned tuple print(str) print(x)
Output:
你好! 2019
Method 4: Use dictionary
In Python, a dictionary is similar to a hash or map in other languages. It consists of key-value pairs; the value can be accessed by its unique key in the dictionary.
Let’s take a look at how to return multiple values in a function through code examples
# 返回一个字典 def fun(): d = dict(); d['name'] = "欧阳克" d['age'] = 25 return d d = fun() print(d)
Output:
{'name': '欧阳克', 'age': 25}
Recommended related video tutorials: "Python Tutorial》《Python3 tutorial》
The above is the detailed content of How to return multiple values in Python function? (code example). For more information, please follow other related articles on the PHP Chinese website!