Question and Answer

how to return multiple values in python

You can return many values from a function in Python.

To achieve this, return a data structure with several values, such as a list of the total number of hours to write every week:

def hours_to_write(happy_hours):
week1 = happy_hours + 2
week2 = happy_hours + 4
week3 = happy_hours + 6
return [week1, week2, week3]
print(hours_to_write(4))
# [6, 8, 10]

Python data structures are intended to contain data collections using functions that can be returned.

In this article, we will see how to return multiple values from such data structures — namely dictionaries, lists, and tuples — as well as with a class and data class (Python 3.7+).

1. Using a Dictionary

A dictionary includes combinations of key values inside curly braces ({}). Every item in a dictionary has a key/value combination. An item consists a key and the corresponding value that creates a pair (key:value). Dictionaries are optimized when the key is known to access values.

Here is a dictionary of people. The name of the person is a key and their age is the corresponding value:

people={
  'Robin': 24,
  'Odin': 26,
  'David': 25
}

This is how to write a function that returns a dictionary with a key/value pair:

# A Python program to return multiple values using dictionary
# This function returns a dictionary
def people_age():
d = dict();
d[‘Jack’] = 30
d[‘Kim’] = 28
d[‘Bob’] = 27
return d
d = people_age()
print(d)
# {‘Bob’: 27, ‘Jack’: 30, ‘Kim’: 28}

2. Using a List

A list is similar to an array of items formed using square brackets, but it is different because it can contain elements of different types. Lists are different from tuples since they are mutable. That means a list can change. Lists are one of Python’s most powerful data structures because lists do not often have to remain similar. A list may include strings, integers, and items. They can even be utilized with stacks as well as queues.

# A Python program to return multiple values using list
def test():
str1 = “Happy”
str2 = “Coding”
return [str1, str2];
list = test()
print(list)
# [‘Happy’, ‘Coding’]

Here’s another example. It returns a list that includes natural numbers:

def natural_numbers(numbers = []):
for i in range(1, 16):
numbers.append(i)
return numbers
print(natural_numbers())
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

3. Using a Tuple

A tuple is an ordered, immutable Python object. Tuples are normally used to store collections of heterogeneous data. Tuples are similar to lists except that they cannot be altered after they are defined. Typically, tuples are quicker than lists. A tuple may be created by separating items with commas: x, y, zor (x, y, z).

The following example uses a tuple to store data about an employee (their name, experience in years, and company name):

Bob = ("Bob", 7, "Google")

Here’s how to write a function that returns a tuple:

# A Python program to return multiple values using tuple
# This function returns a tuple
def fun():
str1 = “Happy”
str2 = “Coding”
return str1, str2; # we could also write (str1, str2)
str1, str2= fun()
print(str1)
print(str2)
# Happy
Codin

Note that we omitted parentheses in the return statement. The reason is you can return a tuple by separating each item with a comma, as shown in the example above.

Keep in mind that the tuple is simply created by the comma — not the parentheses. The parentheses are optional unless you’re using blank tuples or syntactic uncertainty has to be prevented.

Refer to the official Python 3 documentation for further clarity on tuples.

Below is an example of a function that uses parentheses to return a tuple:

def student(name, class):
   return (name, class)
print(student("Brayan", 10))
# ('Brayan', 10)

It’s easy to confuse tuples for lists. After all, they are both bags that consist of items. But note the fundamental difference:

  1. Tuples can’t be altered.
  2. Lists can be altered.

4. Using an Object

This is identical to C/C++ as well as Java. A class (in C, a struct) can be formed to hold several attributes and return a class object:

# A Python program to return multiple values using class
class Intro:
def __init__(self):
self.str1 = “hello”
self.str2 = “world”
# This function returns an object of Intro
def message():
return Intro()
x = message()
print(x.str1)
print(x.str2)
# hello
world

5. Using a Data Class (Python 3.7+)

Using Python 3.7’s data classes, this is how you can return a class with automatically added unique methods, typing, and other useful tools:

from dataclasses import dataclass
@dataclass
class Item_list:
name: str
perunit_cost: float
quantity_available: int = 0
def total_cost(self) -> float:
return self.perunit_cost * self.quantity_available
book = Item_list(“better programming.”, 50, 2)
x = book.total_cost()
print(x)
print(book)
# 100
Item_list(name=‘better programming.’, perunit_cost=50,
quantity_available=2)

See the official documentation for further clarity on data classes.

The Key Takeaway

The primary objective of this article is to help you return several values from a Python function. As we have seen, there are numerous methods you can use to achieve that.

The most crucial point is that you need to learn concepts and develop your programming skills.

Thanks for reading.

Related Articles