In this tutorial, we will learn how to return multiple values (variables). Which are the functions and methods that have that rule? We will cover them all in this tutorial. There are many functions with which we can return multiple values.
These are the functions.
- List
- Tuples
- Dictionary
List in python
Lists are one of the most versatile and widespread data structures in Python. These are used to store an ordered collection of items of various types (numbers, floats, strings, etc.). Lists are mutable, which means you can change, add, or remove them immediately after you create them. Here is an example.
def multiple_values(): a = 10 b = 20 c = 30 return [a, b, c] result = multiple_values() print(result)
output:-[10, 20, 30]
- In this code, we have defined a function called multiple_values() and assigned values.
- The function returns a list containing these three values a,b, and c.
- we call the multiple_values() function and store the result in the result variable.
Tuples in python
A tuple is a collection that is ordered and unchangeable. In Python, tuples are written with round brackets. we can return multiple values as a tuple.
Here is an example.
def multiple_values(): a = 10 b = 20 c = 30 return a, b, c result = multiple_values() print(result)
output:- (10, 20, 30)
- In this code, we have defined a function called multiple_values() and assigned values.
- The function returns a tuple containing these three values a,b, and c.
- we call the multiple_values() function and store the result in the result variable.
Dictionary in python
In a Dictionary, we can return multiple values as key-value pairs. Here is an example.
def multiple_values(): a = 10 b = 20 c = 30 return {'a': a, 'b': b, 'c': c} result = multiple_values() print(result)
output:-{'a': 10, 'b': 20, 'c': 30}
- In this code, we have defined a function called multiple_values() and assigned values.
- The function returns a dictionary containing these three values a,b, and c. where each value is associated with a key
- we call the multiple_values() function and store the result (the dictionary) in the result variable.