Software Dev and QA Tips

How To Return Multiple Values From a Function in Python?

Written by QASource Engineering Team | Feb 17, 2025 5:00:00 PM

Python makes it simple to return multiple values from a function. Several methods suit your needs, whether you need simplicity, mutability, or structure. Here’s an overview of the most common ways to achieve:

  1. Using Tuples: You can return multiple values as a tuple. Tuples are unchangeable and allow you to store several elements within a single variable.
    def get_coordinates(): a = 10 b = 20 return a, b # Returning multiple values as a tuple # Example usage coordinates = get_coordinates() print(coordinates) # Output: (10, 20) print(coordinates[0]) # Access x print(coordinates[1]) # Access y
  2. Using Lists: You can return a list if you need a mutable collection.
    def get_data(): return [1, 2, 3] # Returns as a list # Example usage data = get_data() print(data) # Output: [1, 2, 3]
  3. Using Dictionaries: Returning a dictionary allows you to provide meaningful keys for each value, improving code readability.
    def get_user_info(): return {"name": "Alice", "age": 30} # Example usage user_info = get_user_info() print(user_info['name']) # Output: Alice print(user_info['age']) # Output: 30
  4. Using Objects or NamedTuples: You can use a custom class or namedtuple for structured data.
    NamedTuple
    from collections import namedtuple def get_point(): Point = namedtuple('Point', ['x', 'y']) return Point(5, 10) # Example usage point = get_point() print(point.x) # Output: 5 print(point.y) # Output: 10
    Class
    class User: def __init__(self, name, age): self.name = name self.age = age def get_user(): return User("Bob", 25) # Example usage user = get_user() print(user.name) # Output: Bob print(user.age) # Output: 25
  5. Using Generators: A generator can be used to return values lazily (one at a time).
    def generate_numbers(): yield 1 yield 2 yield 3 # Example usage for num in generate_numbers(): print(num) # Output: 1, then 2, then 3
  6. Using Multiple Return Statements: You can directly return multiple values separated by commas, which Python automatically packs into a tuple.
    def get_colors(): return "red", "green", "blue" # Example usage r, g, b = get_colors() # Unpacking print(r, g, b) # Output: red green blue

Python offers flexible ways to return multiple values, from basic tuples to structured objects. Each method has its use case, so choose the one that best suits your requirements! In summary, you can return multiple values in Python using tuples, lists, dictionaries, objects or namedtuples, generators, or multiple return statements.