Return multiple values from a function call

In this tutorial we learn about get current date and time in python with some cool and easy examples

 Return multiple values from a function call

 

In Python, functions have the flexibility to return multiple values. The ability to return multiple values from a function in Python is a powerful feature that can make your code more flexible and expressive. The choice of method depends on the specific use case:

  • Tuples are simple and straightforward.
  • Lists are useful for a variable number of values.
  • Dictionaries provide named, easily accessible values.
  • NamedTuples and Data Classes offer more structure and readability, especially for more complex data.
 Using Tuples:

Python functions can return a single object, and a tuple allows you to encapsulate multiple values into one immutable object.

def get_ coordinates():
    x = 10
    y = 20
    return x, y
coordinates = get_ coordinates()
print(coordinates)    

output:
(10,20)

Using Lists:

Lists, which are mutable sequences, can also be used to return multiple values. This is useful if the number of values is variable or if the values need to be modified after being returned.

def get_points():
    points = [1, 2, 3, 4, 5]
    return points

# Using the function
points = get_points()
print(points)
output:
[1, 2, 3, 4, 5]

 

Using Dictionary:

Dictionaries allow you to return named values, which can make your code more readable and meaningful by using keys to describe the values.

def get_person_info():
    info = {
        'name': 'John',
        'age': 30,
        'city': 'New York'
    }
    return info

# Using the function
person_info = get_person_info()
print(person_info)     

# Accessing values by keys
print(person_info['name'])  
print(person_info['age'])   
print(person_info['city'])
output:
{'name': 'John', 'age': 30, 'city': 'New York'}
John
30
New York

Using NamedTuples:

Namedtuple from the collections module is a factory function for creating tuple subclasses with named fields, providing more readability and self-documenting code.

from collections import namedtuple

def get_car():
    Car = namedtuple('Car', ['make', 'model', 'year'])
    car = Car(make='Toyota', model='Corolla', year=2021)
    return car

# Using the function
car = get_car()
print(car)
Output:
 Car(make='Toyota', model='Corolla', year=2021)
Using Dataclasses:

Data classes, introduced in Python 3.7, provide a decorator and functions for automatically adding special methods to user-defined classes.

from dataclasses import dataclass
@dataclass
class Employee:
    name: str
    position: str
    salary: float
def get_employee():
    return Employee(name='Alice', position='Developer', salary=75000)
# Using the function
employee = get_employee()
print(employee)         #
output:
  Employee(name='Alice', position='Developer', salary=75000)

Leave a Comment

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

Scroll to Top