How to return an object from a function in Python?


The return statement makes a Python function to exit and hand back a value to its caller. The objective of functions in general is to take in inputs and return something. A return statement, once executed, immediately halts execution of a function, even if it is not the last statement in the function.

Functions that return values are sometimes called fruitful functions.

Example

def sum(a,b):
     return a+b
sum(5,16)

Output

21

Everything in Python, almost everything is an object. Lists, dictionaries, tuples are also Python objects. The code below shows a Python function that returns a Python object; a dictionary.

Example

# This function returns a dictionary
def foo():
     d = dict();
     d['str'] = "Tutorialspoint"
     d['x']   = 50
     return d
print foo()

Output

{'x': 50, 'str': 'Tutorialspoint'}

Updated on: 09-Sep-2023

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements