Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python None Keyword
Next article icon

Returning Multiple Values in Python

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Python




# A Python program to return multiple
# values from a method using class
class Test:
    def __init__(self):
        self.str = "geeksforgeeks"
        self.x = 20
 
# This function returns an object of Test
def fun():
    return Test()
     
# Driver code to test above method
t = fun()
print(t.str)
print(t.x)
 
 
Output
geeksforgeeks 20

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. 

Python




# A Python program to return multiple
# values from a method using tuple
 
# This function returns a tuple
def fun():
    str = "geeksforgeeks"
    x = 20
    return str, x # Return tuple, we could also
                    # write (str, x)
 
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)
 
 
Output
geeksforgeeks 20

  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. 

Python




# A Python program to return multiple
# values from a method using list
 
# This function returns a list
def fun():
    str = "geeksforgeeks"
    x = 20
    return [str, x]
 
# Driver code to test above method
list = fun()
print(list)
 
 
Output
['geeksforgeeks', 20]

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

Python




# A Python program to return multiple
# values from a method using dictionary
 
# This function returns a dictionary
def fun():
    d = dict();
    d['str'] = "GeeksforGeeks"
    d['x'] = 20
    return d
 
# Driver code to test above method
d = fun()
print(d)
 
 
Output
{'x': 20, 'str': 'GeeksforGeeks'}

  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. 

Python3




from dataclasses import dataclass
 
@dataclass
class Book_list:
    name: str
    perunit_cost: float
    quantity_available: int = 0
         
    # function to calculate total cost    
    def total_cost(self) -> float:
        return self.perunit_cost * self.quantity_available
     
book = Book_list("Introduction to programming.", 300, 3)
x = book.total_cost()
 
# print the total cost
# of the book
print(x)
 
# print book details
print(book)
 
# 900
Book_list(name='Python programming.',
        perunit_cost=200,
        quantity_available=3)
 
 
Output
900 Book_list(name='Introduction to programming.', perunit_cost=300, quantity_available=3)

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:

Python3




def get_values():
    yield 42
    yield 'hello'
    yield [1, 2, 3]
 
# Test code
result = get_values()
print(next(result))  # should print 42
print(next(result))  # should print 'hello'
print(next(result))  # should print [1, 2, 3]
 
 
Output
42 hello [1, 2, 3]

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



Next Article
Python None Keyword

S

Shubham Agrawal
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python Functions
    Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
    11 min read
  • Python def Keyword
    Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In Python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In Python def
    6 min read
  • Difference between Method and Function in Python
    Here, key differences between Method and Function in Python are explained. Java is also an OOP language, but there is no concept of Function in it. But Python has both concept of Method and Function. Python Method Method is called by its name, but it is associated to an object (dependent).A method d
    3 min read
  • First Class functions in Python
    First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
    2 min read
  • Assign Function to a Variable in Python
    In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
    4 min read
  • User-Defined Functions

    • Python User Defined Functions
      A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
      6 min read

    • Python User Defined Functions
      A User-Defined Function (UDF) is a function created by the user to perform specific tasks in a program. Unlike built-in functions provided by a programming language, UDFs allow for customization and code reusability, improving program structure and efficiency. Example: [GFGTABS] Python # function de
      6 min read

    • Python | How to get function name ?
      One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
      3 min read

    • Python | How to get function name ?
      One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
      3 min read

    • Defining a Python Function at Runtime
      One amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. It’s especially useful for things like metaprogramming, event-driven systems and running code dynamically
      3 min read

    • Call a function by a String name - Python
      In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between
      3 min read

    • Explicitly define datatype in a Python function
      Unlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
      4 min read

    Built-in and Special Functions

    • Python Built in Functions
      Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
      6 min read

    • Python Lambda Functions
      Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
      7 min read

    • filter() in python
      The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python: Example Usage of filter()[GFGTABS] Python # Function to check if a number is even def even(n): return n % 2
      3 min read

    • Python map() function
      The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
      4 min read

    • reduce() in Python
      The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. This function is defined in "functools" module. Basic Example:Let’s start with a simple example where we sum up all numbers in a list. [GFGTA
      4 min read

    Global and Local Variables

    • Global keyword in Python
      The global keyword in Python allows a function to modify variables that are defined outside its scope, making them accessible globally. Without it, variables inside a function are treated as local by default. It's commonly used when we need to update the value of a global variable within a function,
      5 min read

    • Python Scope of Variables
      In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variabl
      5 min read

    • Accessing Python Function Variable Outside the Function
      In Python, function variables have local scope and cannot be accessed directly from outside. However, their values can still be retrieved indirectly. For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly. Returning the VariableThe most efficient
      4 min read

    Parameters and Arguments

    • Python Function Parameters and Arguments
      Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function. Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function. Although t
      3 min read

    • Keyword and Positional Argument in Python
      Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call. Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Ke
      4 min read

    • How to find the number of arguments in a Python function?
      Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones. Using in
      4 min read

    • Default arguments in Python
      Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value. Default Arguments: Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argu
      7 min read

    • Passing function as an argument in Python
      In Python, functions are first-class objects meaning they can be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, decorators and lambda expressions. By passing a function as an argument, we can modify a function’s behavior dynamically
      6 min read

    • How to get list of parameters name from a function in Python?
      The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
      4 min read

    • How to Pass Optional Parameters to a Function in Python
      In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
      5 min read

    Return Statements

    • How to Pass Optional Parameters to a Function in Python
      In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
      5 min read

    • 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. Python Code # A Python program to return multiple # values from a
      4 min read

    • Python None Keyword
      None is used to define a null value or Null object in Python. It is not the same as an empty string, a False, or a zero. It is a data type of the class NoneType object. None in Python Python None is the function returns when there are no return statements. C/C++ Code def check_return(): pass print(c
      2 min read

    • Returning a function from a function - Python
      In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior. Example: [GFGTABS] Python def fun1(name): def fun2(): return f"Hello, {name}!"
      5 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences