- 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
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Iterator Functions in Python | Set 1
- Python __iter__() and __next__() | Converting an object into an iterator
- Python | Difference between iterable and iterator
- When to use yield instead of return in Python?
- Generators in Python
- Python Functions
Returning Multiple Values in Python
- *args and **kwargs in Python
- Packing and Unpacking Arguments in Python
- First Class functions in Python
- Python Closures
- Decorators in Python
- Help function in Python
- Python | __import__() function
- Python Classes and Objects
- Constructors in Python
- Destructors in Python
- Inheritance in Python
- Python Arrays
- Python If Else
- loops in python
- Loops and Control Statements (continue, break and pass) in Python
- range() vs xrange() in Python
- Using Else Conditional Statement With For loop in Python
- Iterators in Python
- Difficulty Level : Easy
- Last Updated : 27 Dec, 2022
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...

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.
- Define and call functions in Python (def, return)
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
- A tuple with one element requires a comma in Python
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.
- Unpack a tuple and list in Python
Same for three or more return values.
Using [] returns list instead of tuple .
Related Categories
Related articles.
- Random sampling from a list in Python (random.choice, sample, choices)
- Convert pandas.DataFrame, Series and list to each other
- Copy and paste text to the clipboard with pyperclip in Python
- Get calendar as text, HTML, list in Python
- numpy.delete(): Delete rows and columns of ndarray
- Swap values in a list or values of variables in Python
- Generate gradient image with Python, NumPy
- How to use range() in Python
- pandas: Interpolate NaN with interpolate()
- Convert pandas.DataFrame, Series and numpy.ndarray to each other
- pandas: Copy DataFrame to the clipboard with to_clipboard()
- Convert between Unix time (Epoch time) and datetime in Python
- NumPy: np.sign(), np.signbit(), np.copysign()
- Convert a list of strings and a list of numbers to each other in Python
- Deque with collections.deque in Python

- Hire a Top Freelance Talent
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:
- Python return multiple values
- Comma-separated values (Tuples)
- Python List
- Python Dictionary
- Using Python Data Class
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.
- The first two methods, although used extensively, must be used with caution as they do not have the proper names to identify the values and hence can often lead to errors.
- The only difference that list methods have over the tuple method is that lists are mutable.
- The dictionary method is used when you are returning multiple values and find it hard to keep track of their names.
- The Data Class methods can be a little complicated to understand at first, hence I would recommend practicing the other methods and later trying to understand this method.
Other Tutorials
Other related concepts.
- View Freelancers!
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:

If you are a beginner, then I highly recommend this book.
Try the exercises below:
- Create a function that returns a,b and a+b
- Create a function that returns 5 variables
After completing these continue with the next exercise.
Download examples
How to Slice Lists/Arrays in Python
Python Scope of Variables
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
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?
- coding-style
- return-value

- 10 In you excellent examples you use variable y3 , but unless y3 is declared global, this would yield NameError: global name 'y3' is not defined perhaps just use 3 ? – hetepeperfan Dec 19, 2013 at 14:49
- @hetepeperfan no need to change 3, and neither is defining y3 in global, you could also use a local name y3 , that will do the same job too. – okie Oct 27, 2019 at 23:31
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):

- 7 Well, the design rationale for namedtuple is having a smaller memory footprint for mass results (long lists of tuples, such as results of DB queries). For individual items (if the function in question is not called often) dictionaries and classes are just fine as well. But namedtuples are a nice/nicer solution in this case as well. – Lutz Prechelt Feb 23, 2016 at 17:07
- 2 Best answer I think. One thing that I didn't realize immediately - you don't need to declare the namedtuple in the outer scope; your function itself can define the container and return it. – wom Dec 15, 2016 at 14:05
- 12 @wom: Don't do this. Python makes no effort to uniquify namedtuple definitions (each call creates a new one), creating the namedtuple class is relatively expensive in both CPU and memory, and all class definitions intrinsically involve cyclic references (so on CPython, you're waiting for a cyclic GC run for them to be released). It also makes it impossible to pickle the class (and therefore, impossible to use instances with multiprocessing in most cases). Each creation of the class on my 3.6.4 x64 consumes ~0.337 ms, and occupies just under 1 KB of memory, killing any instance savings. – ShadowRanger Apr 20, 2018 at 19:20
- 6 I will note, Python 3.7 improved the speed of creating new namedtuple classes ; the CPU costs drop by roughly a factor of 4x , but they're still roughly 1000x higher than the cost to create an instance, and the memory cost for each class remains high (I was wrong in my last comment about "under 1 KB" for the class, _source by itself is typically 1.5 KB; _source is removed in 3.7, so it's likely closer to the original claim of just under 1 KB per class creation). – ShadowRanger Apr 20, 2018 at 19:31
- 2 @endolith because you can add values after you create it, meaning you can add the results to the retval Namespace as soon as you get them and don't have to wait until you can put them in a named tuple all at once. Can reduce clutter in bigger functions by a lot sometimes. – jaaq Oct 27, 2019 at 12:45
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) .
- 27 Re "returning a dictionary with keys y0, y1, y2 etc doesn't offer any advantage over tuples": dictionary has the advantage in that you can add fields to the returned dictionary without breaking existing code. – ostrokach Aug 28, 2016 at 21:10
- 6 Re "returning a dictionary with keys y0, y1, y2 etc doesn't offer any advantage over tuples": it's also more readable and less error prone as you access the data based on its name rather than position. – Denis Dollfus Jan 16, 2020 at 13:09
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.

- 27 You are still returning a collection. It is a tuple. I prefer parenthesis to make it more explicit. Try this: type(f()) returns <class 'tuple'> . – Igor May 17, 2016 at 18:52
- 28 @Igor: There is no reason to make the tuple aspect explicit; it's not really important that you're returning a tuple , this is the idiom for returning multiple values period. Same reason you omit the parens with the swap idiom, x, y = y, x , multiple initialization x, y = 0, 1 , etc.; sure, it makes tuple s under the hood, but there is no reason to make that explicit, since the tuple s aren't the point at all. The Python tutorial introduces multiple assignment long before it even touches on tuple s. – ShadowRanger Apr 20, 2018 at 19:39
- @ShadowRanger any sequence of values separated by a comma in the right hand side of = is a tuple in Python with or without parenthesis around them. So there's actually no explicit or implicit here. a,b,c is as much a tuple as (a,b,c). There's also no making of tuple "under the hood" when you return such values, because it's just a plain simple tuple. The OP already mentioned tuples so there's actually no difference between what he mentioned and what this answer shows. None – Ken4scholars Jan 23, 2019 at 19:25
- 2 This is the literally the first option suggested in the question – endolith Oct 26, 2019 at 15:43
- 1 @endolith The two times the guy asks a question ("How do I return multiple values?" and "How do you return multiple values?") are answered by this answer. The text of the question has changed sometimes. And it's an opinion-based question. – Joe Hansen Feb 19, 2020 at 14:22
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'.

- 6 after many years of programming, I tend toward what ever the structure of the data and function is required. Function first, you can always refactor as is necessary. – monkut Jun 3, 2014 at 2:59
- How would we get the values within the dictionary without calling the function multiple times? For example, if I want to use y1 and y3 in a different function? – Matt Nov 2, 2014 at 1:19
- 4 assign the results to a separate variable. result = g(x); other_function(result) – monkut Nov 4, 2014 at 1:09
- 1 @monkut yes. This way also allows to pass result to several functions, which take different args from result, without having to specifically reference particular parts of the result every time. – Gnudiff Jan 7, 2018 at 22:45
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.
- 27 This may be "clean", but it doesn't seem intuitive at all. How would someone who's never encountered this pattern before know that doing automatic tuple unpacking would trigger each yield ? – coredumperror Jan 6, 2016 at 21:38
- 1 @CoreDumpError, generators are just that… generators. There is no external difference between def f(x): …; yield b; yield a; yield r vs. (g for g in [b, a, r]) , and both will readily convert to lists or tuples, and as such will support tuple unpacking. The tuple generator form follows a functional approach, while the function form is imperative and will allow flow control and variable assignment. – sleblanc Jan 28, 2019 at 7:14
- Very inventive! Apart from more typing, same as returning a tuple, and not better, not worse – Roland Oct 12, 2022 at 16:21
It seems everything else is just extra code to do the same thing.

- 27 Tuples are easier to unpack: y0, y1, y2 = g() with a dict you have to do: result = g() y0, y1, y2 = result.get('y0'), result.get('y1'), result.get('y2') which is a little bit ugly. Each solution has its 'pluses' and its 'minuses'. – Oli Dec 10, 2008 at 7:46
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.
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.
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.
+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".
"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.

- 2 Donald Knuth said it (in 1974). – Peter Mortensen Jun 20, 2019 at 2:07
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.
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.
- 1 Dicts are mutable. If you pass a dict to a function and that function edits the dict, changes will be reflected outside the scope of that function. Having the function return the dict at the end might imply that the function has no side-effects, therefore the value should not be returned, making it clear that test will directly modify the value. Compare this with dict.update , which does not return a value. – sleblanc Jan 28, 2019 at 7:01
- @sleblanc "Having the function return the dict at the end might imply that the function has no side-effects". It does not imply that because ,as you said, dict is mutable. However, returning form does not hurt readability nor performance. In cases where you may need to reformat form , returning it [form] does make sure that the last form is returned because you will not keep track of form changes anywhere. – Elis Byberi Jan 28, 2019 at 14:03
Not the answer you're looking for? Browse other questions tagged python coding-style return return-value or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- NBA G League free throw
- What is temperature in the classical entropy definition?
- Minimising the environmental effects of my dyson brain
- Full text of the 'Sri Mahalakshmi Dhyanam & Stotram'
- Why is there a voltage on my HDMI and coaxial cables?
- Equation alignment in aligned environment not working properly
- Meanings and roles of 要 inside 信用卡比现金要方便多了。
- Copyright issues when journal is defunct
- Is the God of a monotheism necessarily omnipotent?
- Extracting N elements of the table satisfying the given condition
- Linear Algebra - Linear transformation question
- Disconnect between goals and daily tasks...Is it me, or the industry?
- Google maps for Space exploration
- How would "dark matter", subject only to gravity, behave?
- Relation between transaction data and transaction id
- How Do Subclass Spells Work For Druids?
- Follow Up: struct sockaddr storage initialization by network format-string
- Why do small African island nations perform better than African continental nations, considering democracy and human development?
- Did this satellite streak past the Hubble Space Telescope so close that it was out of focus? If so, how close was it?
- Why does Mister Mxyzptlk need to have a weakness in the comics?
- How do I create endgame tablebases?
- Do "superinfinite" sets exist?
- My code is GPL licensed, can I issue a license to have my code be distributed in a specific MIT licensed project?
- Conjugation of the Auxiliary Verb 得る When it's Read as うる
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 .

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

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

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

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
- Python Tricks
- How to Write to a File in Python
- The with Statement in Python
About the Author
Recent Posts

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
- Display Powers of 2 Using Anonymous Function
- Find Numbers Divisible by Another Number
- Convert Decimal to Binary, Octal and Hexadecimal
- Find ASCII Value of Character
- Find HCF or GCD
- Find the Factors of a Number
- Make a Simple Calculator
Related Topics
Python Nested Dictionary
Python Dictionary Comprehension
- Python Dictionary values()
- Python Set copy()
- Python sorted()
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:
- Python Functions
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:
- Tuples can’t change.
- Lists can change.
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

- Learn Python
- Python Lists
- Python Dictionaries
- Python Strings
- Python Functions
- Learn Pandas & NumPy
- Pandas Tutorials
- Numpy Tutorials
- Learn Data Visualization
- Python Seaborn
- Python Matplotlib
Python: Return Multiple Values from a Function
- October 29, 2021 December 19, 2022

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

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
VIDEO
COMMENTS
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
In Python, you can return multiple values by simply return them separated by commas. ... In Python, comma-separated values are considered tuples
Return multiple values from a function in Python ; #Returning Multiple Values using Tuples · (): operation = "Sum" total = 5 ; #Returning Multiple Values using
Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable
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 =
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
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
This Python tip shows how multiple values can be returned from a Python function (and by implication a Python method). Support my channel on
You can return multiple values from a function in Python. To do so, return a data structure that contains multiple values, like a list
There may be many times when your function returns multiple values, but you only care about