Python Return Multiple Values Tutorial – Complete Guide

Python is a versatile programming language, widely used in a variety of fields like web development, machine learning, data science, and game creation. One of the powerful features of Python is its ability to return multiple values from a function. This tutorial will delve into this functionality, introducing the basics and showing practical code examples. By mastering this aspect of Python, you can not only write more efficient and clean code, but also open up new possibilities in your programming tasks. Whether you’re starting on your coding journey or an experienced coder looking to refine your skills, this tutorial offers valuable insights.

What Is ‘Return Multiple Values’ in Python?

In Python, ‘Return Multiple Values’ refers to the ability of a function to return more than one value upon its execution. These values can be of various data types like integers, floats, strings, lists, tuples, and more.

This feature is used when you want to get more than one result from a function execution. Instead of writing separate functions for each output or complicating a function with multiple print statements, you can use this feature to make your code more concise and efficient.

Learning how to return multiple values in Python can give your programming prowess a substantial boost. It not only makes your code more efficient, but also simplifies the process of debugging and maintenance. Especially in game creation and data manipulation tasks, this feature can be a powerful tool to enhance your productivity.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

How to Return Multiple Values in Python

Let’s start with the basics. To return multiple values from a function in Python, we use the return statement. We typically pack these multiple values inside a tuple, a list, or a dictionary and return it to the caller.

Here’s a basic example of a function using a tuple:

def func():
  return 1, 2, 3
print(func())

The output will be:

(1, 2, 3)

Notice how the tuple is automatically formed without parentheses. This is known as tuple packing.

We can also use lists to return multiple values:

def func():
  return [1, 2, 3]
print(func())

The output will be:

[1, 2, 3]

Just like with tuples, we can pack multiple values into a list and return it.

Unpacking Values Returned from a Function

When we receive multiple values from a function, we can assign them separately using a process known as ‘unpacking’. Let’s take a look:

def func():
  return 1, 2, 3
a, b, c = func()
print(a, b, c)

The output will be:

1 2 3

As you see, the returned tuple (1, 2, 3) has been ‘unpacked’ into variables a, b, and c.

Returning Multiple Values using Dictionaries

Sometimes, it’s more efficient to return values in a dictionary, especially when the function returns many values. Let’s see an example:

def func():
  return {'a': 1, 'b': 2, 'c': 3}
result = func()
print(result)

The output will be:

{'a': 1, 'b': 2, 'c': 3}

As you can see, we can return key-value pairs for more complicated scenarios.

Named Tuple for Clearer Returns

For enhancing readability, Python offers named tuples. Named tuples are tuples that allow you to access its elements via named attributes.

from collections import namedtuple

def func():
    Person = namedtuple('Person', 'name age')
    return Person(name='John', age=30)

p = func()
print(p.name)
print(p.age)

The output will be:

John
30

The function returns a Person object that has attributes name and age. This greatly enhances readability when we are dealing with complex returns.

Combining Tuples, Lists, and Dictionaries

One great aspect of Python is that you can combine different data types for returning multiple values. Let’s see an example:

def func():
    return [1, 2], {3, 4}, {'five': 5, 'six': 6}

a, b, c = func()
print(a)
print(b)
print(c)

The output will be:

[1, 2]
{3, 4}
{'five': 5, 'six': 6}

You can see that our function has returned a list, a set, and a dictionary. We are not limited to returning just one type of data structure.

Returning Functions

Python also allows you to return functions from a function. This opens up a world of possibilities for function composition and functional programming.

def greet(name):
    def greeting():
        return f"Hello, {name}!"
    return greeting

hello_func = greet('John')
print(hello_func())

The output will be:

Hello, John!

The function greet returns another function greeting which when called prints out a greeting message. This technique can be very powerful in complex programming tasks.

Null Returns

What happens when a function does not explicitly return a value? Python, by default, returns None.

def func():
    pass

print(func())

The output will be:

None

If we don’t specify a return value, Python returns None. Keep this in mind when designing your functions.

Where to Go Next

By now, you should have a good grasp of returning multiple values in Python. But remember, mastering programming is a journey of continuous learning and practice. To really hone your skills, it’s important to delve deep into the basics and explore the advanced functionalities.

One excellent way to continue with your Python journey is to check out our Python Mini-Degree. It’s a comprehensive collection of courses designed to teach Python programming from the ground up. You’ll learn coding basics, algorithms, object-oriented programming, game development, and app development, all while using Python.

The mini-degree familiarizes you with popular libraries and frameworks like Pygame, Tkinter, Kivy, and PySimpleGUI. These courses are designed with both beginners and experienced programmers in mind, with project-based assignments and flexible learning options.

For an even broader collection of Python resources and ongoing learning, check out our complete range of Python courses on Zenva Academy.

Conclusion

Diving into the intricacies of Python, such as returning multiple values, sharpens your programming skills and enables you to write more efficient and cleaner code. More importantly, it arms you with the knowledge to tackle real-world programming challenges across various fields, from web development, game creation, to data analysis, and more.

Unlock your full Python potential by learning with Zenva. Take the first step in fortifying your programming foundation with our Python Mini-Degree. Packed with rich content and immersive courses, it’s the ideal companion for your journey from beginner to advanced Python programmer. Develop your skills, build your portfolio, and advance your programming career with Zenva.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.