Javatpoint Logo
Javatpoint Logo

Return Two Values from a Function Python

A specified activity, which almost certainly includes returning a particular value, is performed by functions. Some use cases, though, can call for you to give two or more answers. Other scripting languages could require quite a bit of code to accomplish this, but Python has a few useful methods for returning multiple results.

The majority of these techniques return these values as a collection data type. All of them have been carefully examined below.

Return Values Using a Comma

Code

Output

('Python', 'Java')
Python Java

Using Class and Object

The ability to construct a class (in C, a struct) to store multiple items and return an instance of the class is analogous to Java and C/C++.

Code

Output

JavatpointPython
20

Using a Tuple

A series of things separated by commas is known as a tuple. It can be made either way (). We cannot change tuples.

Code

Output

('Python', 'Java')
Python Java

Using a List

An array of objects constructed with square brackets is similar to a list. They vary from arrays in that they can include objects of various sorts. Tuples are static, whereas we can modify lists.

Code

Output

['Python', 'Java']

Using a Dictionary

It would be difficult to access a specific value using the prior technique. While utilizing dictionaries to return multiple values, this wouldn't be an issue. This is so that they could be conveniently retrieved, and we could choose appropriate key names.

Code

Output

{'string1': 'Python', 'string2': 'Java'}

Using Python Data Class

Data Classes are used in this approach to return two values. A user-defined class can have particular methods added using data classes. Version 3.7 of Python saw the introduction of this technique.

Code

Output

16
twovalues(operation='Addition Operation', n1=6, n2=10)






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA