Python is a highly versatile programming language and like most programming languages, python has a feature called the function Ignore Python Multiple Return values. For people who don’t know what functions are, functions are “self-contained” modules of code that accomplish a specific task.
Functions usually “take in” data, process it, and “return” a result. Once a function is written, it can use over and over and over again.
Functions can be “called” from the inside of other functions. In this article, we will talk about how you can return multiple values from a function. So without further ado, let us get straight into it ignore python multiple return values.
USING OBJECTS
This method is similar to the methods of C/C++ and Java since we can create a class to hold multiple values then use an object to return those values. For example.
class Test: def __init__(self): self.str = "hello" self.x = 10 def fun(): return Test() t = fun() print(t.str) print(t.x) Output hello 10 def fun(): str = "hello" x = 10 return [str, x]; list = fun() print(list)
Output:
[‘hello’, 10]
Explanation:
- First, we created a class called Test and initialized some values that we can later call using an object.
- Next, we created a method called fun which will simply return the object of the class Test.
- Then finally, we created an object of Test called t, and finally, we called 2 methods using the instance that we just created.
USING A LIST
In python, a list is like an array of items created using square brackets. The only difference is that python lists can store different types of items.
Explanation
In the very first step, we created a class called fun and initialized a variable “str” to hold a string of “hello”. We also created a variable x that holds a value of 10.
Next, simply returned a list that will hold 2 items; str and x. Then we created an object “list” of the class “fun” and then the program automatically printed a list that stores both of the pre-defined values.
USING A DICTIONARY
A python dictionary is similar to a list but with a few differences. Also, a dictionary is similar to a hash or map in other languages.
In simple words, a dictionary is a general-purpose data structure for storing a group of objects. A dictionary has a set of keys and each key has a single associated value.
def fun(): d = dict(); d['str'] = "hello" d['x'] = 10 return d d = fun() print(d)
Output
{‘x’: 10, ‘str’: ‘hello’}
Explanation
- In the first step, we created a class called fun and immediately declared a function called dict.
- Next, we created 2 variables and gave them values of our choice After that, we returned the function we created earlier.
- Now, we create an object of the class fun through which we can access the methods.