• Data Structure & Algorithm Classes (Live)
  • System Design (Live)
  • DevOps(Live)
  • Explore More Live Courses
  • Interview Preparation Course
  • Data Science (Live)
  • GATE CS & IT 2024
  • Data Structure & Algorithm-Self Paced(C++/JAVA)
  • Data Structures & Algorithms in Python
  • Explore More Self-Paced Courses
  • C++ Programming - Beginner to Advanced
  • Java Programming - Beginner to Advanced
  • C Programming - Beginner to Advanced
  • Android App Development with Kotlin(Live)
  • Full Stack Development with React & Node JS(Live)
  • Java Backend Development(Live)
  • React JS (Basic to Advanced)
  • JavaScript Foundation
  • Complete Data Science Program(Live)
  • Mastering Data Analytics
  • CBSE Class 12 Computer Science
  • School Guide
  • All Courses
  • Linked List
  • Binary Tree
  • Binary Search Tree
  • Advanced Data Structure
  • All Data Structures
  • Asymptotic Analysis
  • Worst, Average and Best Cases
  • Asymptotic Notations
  • Little o and little omega notations
  • Lower and Upper Bound Theory
  • Analysis of Loops
  • Solving Recurrences
  • Amortized Analysis
  • What does 'Space Complexity' mean ?
  • Pseudo-polynomial Algorithms
  • Polynomial Time Approximation Scheme
  • A Time Complexity Question
  • Searching Algorithms
  • Sorting Algorithms
  • Graph Algorithms
  • Pattern Searching
  • Geometric Algorithms
  • Mathematical
  • Bitwise Algorithms
  • Randomized Algorithms
  • Greedy Algorithms
  • Dynamic Programming
  • Divide and Conquer
  • Backtracking
  • Branch and Bound
  • All Algorithms
  • Company Preparation
  • Practice Company Questions
  • Interview Experiences
  • Experienced Interviews
  • Internship Interviews
  • Competitive Programming
  • Design Patterns
  • System Design Tutorial
  • Multiple Choice Quizzes
  • Go Language
  • Tailwind CSS
  • Foundation CSS
  • Materialize CSS
  • Semantic UI
  • Angular PrimeNG
  • Angular ngx Bootstrap
  • jQuery Mobile
  • jQuery EasyUI
  • React Bootstrap
  • React Rebass
  • React Desktop
  • React Suite
  • ReactJS Evergreen
  • ReactJS Reactstrap
  • BlueprintJS
  • TensorFlow.js
  • English Grammar
  • School Programming
  • Number System
  • Trigonometry
  • Probability
  • Mensuration
  • Class 8 Syllabus
  • Class 9 Syllabus
  • Class 10 Syllabus
  • Class 8 Notes
  • Class 9 Notes
  • Class 10 Notes
  • Class 11 Notes
  • Class 12 Notes
  • Class 8 Maths Solution
  • Class 9 Maths Solution
  • Class 10 Maths Solution
  • Class 11 Maths Solution
  • Class 12 Maths Solution
  • Class 7 Notes
  • History Class 7
  • History Class 8
  • History Class 9
  • Geo. Class 7
  • Geo. Class 8
  • Geo. Class 9
  • Civics Class 7
  • Civics Class 8
  • Business Studies (Class 11th)
  • Microeconomics (Class 11th)
  • Statistics for Economics (Class 11th)
  • Business Studies (Class 12th)
  • Accountancy (Class 12th)
  • Macroeconomics (Class 12th)
  • Machine Learning
  • Data Science
  • Mathematics
  • Operating System
  • Computer Networks
  • Computer Organization and Architecture
  • Theory of Computation
  • Compiler Design
  • Digital Logic
  • Software Engineering
  • GATE 2024 Live Course
  • GATE Computer Science Notes
  • Last Minute Notes
  • GATE CS Solved Papers
  • GATE CS Original Papers and Official Keys
  • GATE CS 2023 Syllabus
  • Important Topics for GATE CS
  • GATE 2023 Important Dates
  • Software Design Patterns
  • HTML Cheat Sheet
  • CSS Cheat Sheet
  • Bootstrap Cheat Sheet
  • JS Cheat Sheet
  • jQuery Cheat Sheet
  • Angular Cheat Sheet
  • Facebook SDE Sheet
  • Amazon SDE Sheet
  • Apple SDE Sheet
  • Netflix SDE Sheet
  • Google SDE Sheet
  • Wipro Coding Sheet
  • Infosys Coding Sheet
  • TCS Coding Sheet
  • Cognizant Coding Sheet
  • HCL Coding Sheet
  • FAANG Coding Sheet
  • Love Babbar Sheet
  • Mass Recruiter Sheet
  • Product-Based Coding Sheet
  • Company-Wise Preparation Sheet
  • Array Sheet
  • String Sheet
  • Graph Sheet
  • ISRO CS Original Papers and Official Keys
  • ISRO CS Solved Papers
  • ISRO CS Syllabus for Scientist/Engineer Exam
  • UGC NET CS Notes Paper II
  • UGC NET CS Notes Paper III
  • UGC NET CS Solved Papers
  • Campus Ambassador Program
  • School Ambassador Program
  • Geek of the Month
  • Campus Geek of the Month
  • Placement Course
  • Testimonials
  • Student Chapter
  • Geek on the Top
  • Geography Notes
  • History Notes
  • Science & Tech. Notes
  • Ethics Notes
  • Polity Notes
  • Economics Notes
  • UPSC Previous Year Papers
  • SSC CGL Syllabus
  • General Studies
  • Subjectwise Practice Papers
  • Previous Year Papers
  • SBI Clerk Syllabus
  • General Awareness
  • Quantitative Aptitude
  • Reasoning Ability
  • SBI Clerk Practice Papers
  • SBI PO Syllabus
  • SBI PO Practice Papers
  • IBPS PO 2022 Syllabus
  • English Notes
  • Reasoning Notes
  • Mock Question Papers
  • IBPS Clerk Syllabus
  • Apply for a Job
  • Apply through Jobathon
  • Hire through Jobathon
  • All DSA Problems
  • Problem of the Day
  • GFG SDE Sheet
  • Top 50 Array Problems
  • Top 50 String Problems
  • Top 50 Tree Problems
  • Top 50 Graph Problems
  • Top 50 DP Problems
  • Solving For India-Hackthon
  • GFG Weekly Coding Contest
  • Job-A-Thon: Hiring Challenge
  • BiWizard School Contest
  • All Contests and Events
  • Saved Videos
  • What's New ?
  • Data Structures
  • Interview Preparation
  • Topic-wise Practice
  • Latest Blogs
  • Write & Earn
  • Web Development

Related Articles

Returning Multiple Values in Python

In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. 

Below are interesting methods for somebody shifting C++/Java world. 

  2) Using Tuple: A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are immutable. See this for details of tuple and list. 

  3) Using a list: A list is like an array of items created using square brackets. They are different from arrays as they can contain items of different types. Lists are different from tuples as they are mutable. 

  4) Using a Dictionary: A Dictionary is similar to hash or map in other languages. See this for details of dictionary. 

  5) Using Data Class (Python 3.7+): In Python 3.7 and above the Data Class can be used to return a class with automatically added unique methods. The Data Class module has a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() in the user-defined classes. 

6.  Using ‘yield’

One alternative approach for returning multiple values from a function in Python is to use the yield keyword in a generator function. A generator function is a special type of function that returns an iterator object, which generates a sequence of values on the fly, one value at a time.

To return multiple values from a generator function, you can use the yield keyword to yield each value in turn. The generator function will then pause execution until the next value is requested, at which point it will resume execution and yield the next value. This process continues until the generator function completes execution or encounters a return statement.

Here is an example of how this can be done:

Time complexity : O(1) because it only performs a constant number of operations (yields) regardless of the size of the input.  Auxiliary space: O(1) because it only stores a constant number of variables (yielded values) in memory at any given time.

Reference: http://stackoverflow.com/questions/354883/how-do-you-return-multiple-values-in-python This article is contributed by Shubham Agrawal . If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Please Login to comment...

python assign multiple outputs

Improve your Coding Skills with Practice

Start your coding journey now.

note.nkmk.me

How to return multiple values from a function in python.

This article describes how to return multiple values from a function in Python.

Return multiple values using commas

Return list.

See the following article for the basics of functions in Python.

In Python, you can return multiple values by simply return them separated by commas.

As an example, define a function that returns a string and a integer as follows:

In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

Note that it is actually the comma which makes a tuple, not the parentheses. The parentheses are optional, except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. Built-in Types - Tuples — Python 3.7.4 documentation

Each element has a type defined in the function.

Of course, specifying an index that exceeds the number of defined return values raises an error.

You can unpack and assign multiple return values to different variables.

Same for three or more return values.

Using [] returns list instead of tuple .

Related Categories

Related articles.

python assign multiple outputs

Return multiple values from a function in Python

In this guide, we look at Python: Return multiple values from a function. We explain the various methods in detail and list their shortcomings.

Table of Contents - Python return multiple values:

Limitations and Caveats - Python return multiple values

Python return multiple values:.

Functions are used to perform a specific task which most likely involves returning a particular value. However, a few use-cases may require you to return two or more values. In other programming languages, the code to achieve this might be quite complex but Python provides a few handy methods to return multiple values.

Most of these methods involve using a collection data type to return these values. We have taken a close look at all of them below.

Using Comma-separated values (Tuples):

In this method, we use Python to return multiple values by simply separating them by commas. Python basically uses a tuple to achieve this.

A common confusion here is that the syntax of tuple requires a pair of brackets (). Although this is true, Python does not always require brackets to identify a tuple.

Using Python Lists:

Similar to the previous methods, lists can also be used to return multiple values, too. In case you are not familiar with lists, they are a collection of items. They are quite similar to arrays however they can be used to store values of various data types.

Since they are a collection of items we could add values to the list and return the list.

In this method, you would have to use the index of the list to use the values individually.

Using a Python Dictionary:

In the previous method, accessing a particular value would be a hassle. However, this would not be a problem while using dictionaries to return multiple values. This is because we could use relevant key names and they could be accessed easily.

In this method, the returned values can easily be accessed within their keys.

Using a Python Data Class:

In this method, we use Data Classes to return multiple values. Data classes are a method of adding specific methods to a user-defined class. This method was introduced in Python version 3.7.

Other Tutorials

Other related concepts.

Multiple return

Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables.

This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.

Related course: Complete Python Programming Course & Exercises

Introduction

Variables defined in a function are only known in the function. That’s because of the scope of the variable. In general that’s not a problem, unless you want to use the function output in your program.

In that case you can return variables from a function. In the most simple case you can return a single variable:

Call the function with complexfunction(2,3) and its output can be used or saved.

But what if you have multiple variables in a function that you want access to?

Create a function getPerson(). As you already know a function can return a single variable, but it can also return multiple variables.

This will output:

multiple return

If you are a beginner, then I highly recommend this book.

Try the exercises below:

After completing these continue with the next exercise.

Download examples

How to Slice Lists/Arrays in Python

Python Scope of Variables

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Alternatives for returning multiple values from a Python function [closed]

The canonical way to return multiple values in languages that support it is often tupling .

Option: Using a tuple

Consider this trivial example:

However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.

Option: Using a dictionary

The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a dict .

Consider the following:

(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)

Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,

Option: Using a class

However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:

In Python the previous two are perhaps very similar in terms of plumbing - after all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue .

There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:

From the Python Reference Manual :

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

Option: Using a dataclass (Python 3.7+)

Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:

Option: Using a list

Another suggestion which I'd overlooked comes from Bill the Lizard:

This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.

A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable , whereas tuples are not.

I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.

After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?

divenex's user avatar

14 Answers 14

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

Example (From the docs):

ShadowRanger's user avatar

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

Returning a dictionary with keys "y0" , "y1" , "y2" , etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0 , .y1 , .y2 , etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file) .

Boris Verkhovskiy's user avatar

A lot of the answers suggest you need to return a collection of some sort, like a dictionary or a list. You could leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.

Joe Hansen's user avatar

I vote for the dictionary.

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

monkut's user avatar

Another option would be using generators:

Although IMHO tuples are usually best, except in cases where the values being returned are candidates for encapsulation in a class.

rlms's user avatar

It seems everything else is just extra code to do the same thing.

Peter Mortensen's user avatar

I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.

I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.

For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.

tzot's user avatar

Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.

I like to find names for anonymous structures where possible. Meaningful names make things more clear.

S.Lott's user avatar

Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct for data-only items and class for objects with methods, even though you can legally put methods on a struct ; my habit is similar in Python, with dict and tuple in place of struct .

For coordinate sets, I'll use a tuple rather than a point class or a dict (and note that you can use a tuple as a dictionary key, so dict s make great sparse multidimensional arrays).

If I'm going to be iterating over a list of things, I prefer unpacking tuple s on the iteration:

...as the object version is more cluttered to read:

...let alone the dict .

If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.

Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict because that's best suited to JSON serialization.

Russell Borogove's user avatar

+1 on S.Lott's suggestion of a named container class.

For Python 2.6 and up, a named tuple provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples".

John Fouhy's user avatar

"Best" is a partially subjective decision. Use tuples for small return sets in the general case where an immutable is acceptable. A tuple is always preferable to a list when mutability is not a requirement.

For more complex return values, or for the case where formality is valuable (i.e. high value code) a named tuple is better. For the most complex case an object is usually best. However, it's really the situation that matters. If it makes sense to return an object because that is what you naturally have at the end of the function (e.g. Factory pattern) then return the object.

As the wise man said:

Premature optimization is the root of all evil (or at least most of it) in programming.

joel3000's user avatar

In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.

However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.

fluffels's user avatar

I would use a dict to pass and return values from a function:

Use variable form as defined in form .

This is the most efficient way for me and for processing unit.

You have to pass just one pointer in and return just one pointer out.

You do not have to change functions' (thousands of them) arguments whenever you make a change in your code.

Elis Byberi's user avatar

Not the answer you're looking for? Browse other questions tagged python coding-style return return-value or ask your own question .

Hot Network Questions

python assign multiple outputs

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

codingem.com

software development and tech.

How to Return Multiple Values from a Python Function

To return multiple values from a Python function, use a comma to separate the return values.

For instance, let’s create a function that takes two numbers as arguments. This function returns the sum, difference, multiplication, and division between these two numbers.

Here is how it looks in the code:

Now you can call this function for two numbers and assign the return values to variables:

This results in the following being printed in the console:

How Does Returning Multiple Values Work in Python

In the previous section, you learned how to return multiple values by comma-separating the values.

But why and how does it work?

Tuples in Python

Tuple is a comma-separated list of values in Python

The example code works because it returns a tuple.

In case you don’t know what a tuple is, check out this in-depth article . In short, a tuple is a group of zero or more elements.

For instance, here is an example of a tuple of three values that represents a 3D point:

Notice that Python tuples do not always need parenthesis.

For example, you can write the above 3D point as:

This creates the same tuple of three values that represent a 3D point.

How to Access a Tuple Value in Python

To access and store a value from a tuple you can access it like you would access a value from a list. In other words, use the [] operator with an index.

For example, let’s store the 3D points into variables x, y, and z:

This results in the following output in the console:

This works fine, but there is an easier way for this particular purpose.

Tuple Destructuring in Python

Tuple destructuring

You can use tuple destructuring to access tuple values and store them into variables.

Tuple destructuring means you declare a bunch of comma-separated variables in one line and assign each tuple value to the corresponding variable. This saves you lines of code meanwhile it also makes the intention very clear.

Let me show what I mean

For instance, in the previous example, you stored 3D coordinates x , y , and z on separate lines using the [] operator. Instead of doing it this way, you can utilize tuple destructuring as a shorthand:

As a result, each coordinate in the 3D point is assigned to a separate variable.

As you can see, the first value of the tuple was attached to variable x , the second one to y , and the third one to z .

Now you understand how tuples are created and how values are read from them.

How to Return Multiple Values from a Function

Return multiple values in Python function by using commas

To return multiple values from a function, return the values as a tuple. To then access/store these values into variables, use tuple destructuring.

If you now look at the example you saw in the introduction:

You recognize this function returns a tuple of four values. To access these four values, you use tuple restructuring. Here’s how it looks in code:

Now the returned tuple values are stored in the variables sum , diff , mul , and div .

Destructuring a returned tuple this way is handy. You don’t need to use the square-bracket accessing operator to manually pick the values from the tuple. Instead, the destructuring syntax takes care of that.

To return multiple values from a function in Python, return a tuple of values.

As you may know, a tuple is a group of comma-separated values. You can create a tuple with or without parenthesis. To access/store the multiple values returned by a function, use tuple destructuring.

Thanks for reading. Happy coding!

Further Reading

About the Author

' src=

Recent Posts

python assign multiple outputs

Become a Job-Ready Developer

Get tips on how to become a job-ready software developer in no time.

Learn Python interactively.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials.

Learn Python Interactively

Python Examples

Related Topics

Python Nested Dictionary

Python Dictionary Comprehension

Python Closures

Python Program to Return Multiple Values From a Function

In this example, you will learn to return multiple values from a function.

To understand this example, you should have the knowledge of the following Python programming topics:

Example 1: Return values using comma

When you return multiple values using comma(s), they are returned in the form of a tuple. As shown in the code above, two strings "John" and "Armin" are returned with a single return statement.

Example 2: Using a dictionary

When you return values using a dictionary, it is easy for you to keep track of the returned values using the keys. The return statement returns the two variables in the form a dictionary.

Sorry about that.

Related Examples

Python Tutorial

Python Dictionary

Try PRO for FREE

Python Return Multiple Values – How to Return a Tuple, List, or Dictionary

You can return multiple values from a function in Python.

To do so, return a data structure that contains multiple values, like a list containing the number of miles to run each week.

Data structures in Python are used to store collections of data, which can be returned from  functions. In this article, we’ll explore how to return multiple values from these data structures: tuples, lists, and dictionaries.

A tuple is an ordered, immutable sequence. That means, a tuple can’t change.

Use a tuple, for example, to store information about a person: their name, age, and location.

Here’s how you’d write a function that returns a tuple.

Notice that we didn’t use parentheses in the return statement. That’s because you can return a tuple by separating each item with a comma, as shown in the above example.

“It is actually the comma which makes a tuple, not the parentheses,” the documentation points out. However, parentheses are required with empty tuples or to avoid confusion.

Here’s an example of a function that uses parentheses () to return a tuple.

A list is an ordered, mutable sequence. That means, a list can change.

You can use a list to store cities:

Or test scores:

Take a look at the function below. It returns a list that contains ten numbers.

Here’s another example. This time we pass in several arguments when we call the function.

It’s easy to confuse tuples and lists. After all, both are containers that store objects. However, remember these key differences:

Dictionaries

A dictionary contains key-value pairs wrapped in curly brackets {} . Each “key” has a related “value.”  

Consider the dictionary of employees below. Each employee name is a “key” and their position is the “value.”

Here’s how you’d write a function that returns a dictionary with a key, value pair.

In the above example, “Boston” is the key and “United States” is the value .  

We’ve covered a lot of ground. The key point is this: you can return multiple values from a Python function, and there are several ways to do so.

I write about the programming skills you need to develop and the concepts you need to learn, and the best ways to learn them at amymhaddad.com .

Programmer and writer | howtolearneffectively.com | dailyskillplanner.com

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Datagy logo

Python: Return Multiple Values from a Function

Python Return Multiple Values from Function Cover Image

In this tutorial, you’ll learn how to use Python to return multiple values from your functions . This is a task that is often quite difficult in some other languages, but very easy to do in Python.

You’ll learn how to use tuples, implicitly or explicitly, lists, and dictionaries to return multiple values from a function. You’ll also learn how to identify which method is best suited for your use case. You’ll also learn how to unpack items of unequal length, using the unpacking operator ( * ).

Being able to work with functions is an incredibly useful skill that allows you to more readily follow the DRY (don’t repeat yourself) principle. Functions allow your code to be significantly more readable and less repetitive. All of this allows your code to be more maintainable and reduces complexity of the code.

The Quick Answer: Use Tuple Unpacking

Quick Answer - Python Return Multiple Values from Function

Table of Contents

How do Functions Return Values in Python?

Python functions are easy ways to structure code into dynamic processes that are readable and reusable. While Python functions can accept inputs, in this tutorial, we’ll be looking at function outputs . Specifically, we’ll be look at how functions return values.

Let’s take a look at how a function in Python is designed and how to return one value and how to return two values.

In the example above, we have defined two different functions, return_one() and return_two() . The former of these returns only a single value. Meanwhile, the latter function, return_two() , returns two values. This is done by separating the values by commas.

In the next section, you’ll learn how and why returning multiple values actually works.

Want to learn more about calculating the square root in Python? Check out my tutorial here , which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

How to Return Multiple Values from a Python Function with Tuples

In the previous section, you learned how to configure a Python function to return more than a single value.

The way that this works, is that Python actually turns the values (separated by commas) into a tuple. We can see how this works by assigning the function to a variable and checking its type.

We can see in the code above that when we assign our function to a variable, that a tuple is generated.

This may surprise you, however, since you don’t actually tell the function to return (1, 2, 3) . Python implicitly handles converting the return values into a tuple. It’s not the parentheses that turn the return value into a tuple, but rather the comma along with the parentheses.

We can verify this by checking the type of the value (1), for example. This returns: int .

Again, this might surprise you. If we changed our value to (1,) , however, we return a different result.

A lot of this may seem like semantics, but it allows you to understand why these things actually work. Now, let’s learn how to assign these multiple variables to different variables.

Let’s look at the same function as before. Instead of assigning the return values to a single tuple, let’s unpack our tuple and return three separate values .

The reason this works is that Python is handling unpacking these values for us. Because we have the same number of assignment variables as we do values in the return statement, Python handles the assignment of these values for us.

In the next section, you’ll learn how to unpack multiple values from a Python to variables with mismatched lengths.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here .

How to Unpack Multiple Values from a Python Function to Unequal Lengths

In the example above, you learned how to return multiple values from a Python function by unpacking values from the return tuple.

There may be many times when your function returns multiple values, but you only care about a few. You don’t really care about the other values, but Python will not let you return only a few of them.

Let’s see what this looks like:

This happens because our assignment needs to match the number of items returned.

However, Python also comes with an unpacking operator , which is denoted by * . Say that we only cared about the first item returned. We still need to assign the remaining values to another variable, but we can easily group them into a single variable, using the unpacking operator.

Let’s see how this works in Python:

Here, we have unpacked the first value to our variable a , and all other variables to the variable b , using the notation of *b .

In the next section, you’ll learn how to return multiple values from a Python function using lists.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

How to Return Multiple Values from a Python Function with Lists

Similar to returning multiple values using tuples, as shown in the previous examples, we can return multiple values from a Python function using lists.

One of the big differences between Python sets and lists is that lists are mutable in Python , meaning that they can be changed. If this is an important characteristic of the values you return, then this is a good way to go.

Let’s see how we can return multiple values from a function, using both assignment to a single variable and to multiple variables.

In the next section, you’ll learn how to use Python dictionaries to better understand return values.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here .

How to Return Multiple Values from a Python Function with Dictionaries

In both examples above, if you’re returning all values to a single variable, it can be difficult to determine what each value represents. For example, while you can access all the items in a tuple or in a list using indexing, it can be difficult to determine what each value represents.

Let’s take a look at a more complicated function that creates variables for speed , time , and distance travelled for a car.

If we returned this as a tuple or as a list, then we would need to know which variable represents what item. However, we can also return these items as a dictionary. When we do this, we can access each item by its key .

Let’s see how we can do this in Python:

Need to check if a key exists in a Python dictionary? Check out this tutorial , which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

In this tutorial, you learned how to return multiple values from Python functions. You learned how and why multiple values can be returned and how to optimize how values are returned for your use cases, by learning how to return tuples, lists, and dictionaries. You also learned how to unpack multiple values to variables of different lengths.

To learn more about Python functions, check out the official documentation here .

1 thought on “Python: Return Multiple Values from a Function”

Pingback:  Functions in Python • datagy

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

IMAGES

  1. Return Multiple Values from A Python Function

    python assign multiple outputs

  2. Python Assign Expression To A Variable Andit Stack

    python assign multiple outputs

  3. Create Python Variables

    python assign multiple outputs

  4. Python Tutorial For Beginners

    python assign multiple outputs

  5. Python Variables

    python assign multiple outputs

  6. Python Variables with examples

    python assign multiple outputs

VIDEO

  1. input in python

  2. python programming tutorial -Ep09: input/output in python

  3. Cubase Multiple Outputs

  4. multiple variable assignments in Python

  5. 04

  6. Blender Quick Tips

COMMENTS

  1. Returning Multiple Values in Python

    To return multiple values from a generator function, you can use the yield keyword to yield each value in turn. The generator function will then

  2. How to return multiple values from a function in Python

    In Python, you can return multiple values by simply return them separated by commas. ... In Python, comma-separated values are considered tuples

  3. Return multiple values from a function in Python

    Return multiple values from a function in Python ; #Returning Multiple Values using Tuples · (): operation = "Sum" total = 5 ; #Returning Multiple Values using

  4. Multiple return

    Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable

  5. Alternatives for returning multiple values from a Python function

    The canonical way to return multiple values in languages that support it is often tupling. Option: Using a tuple. Consider this trivial example: def f(x): y0 =

  6. How to Return Multiple Values from a Python Function

    To return multiple values from a Python function, use a comma to separate the return values. For instance, let's create a function that takes two numbers as

  7. Python Program to Return Multiple Values From a Function

    When you return multiple values using comma(s), they are returned in the form of a tuple. As shown in the code above, two strings "John" and "Armin" are

  8. Python Tip: Returning multiple values from a function

    This Python tip shows how multiple values can be returned from a Python function (and by implication a Python method). Support my channel on

  9. Python Return Multiple Values

    You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list

  10. Python: Return Multiple Values from a Function

    There may be many times when your function returns multiple values, but you only care about