Skip to content

Python callback function

  • by

Python callback function is a function that is passed as an argument to another function and is then called inside the parent function. The callback function is to allow for more dynamic and flexible programming by enabling the parent function to call different functions based on different conditions.

It can be done in two ways:

  1. Passing one function as an argument to another function
  2. Calling a function inside another function

Python callback function example

Simple example code Callback in user-defined functions.

def apply_callback(value, callback):  # callback -> print_result
print("apply_callback")
res = value * 2
return callback(res)


def print_result(result):
print("print_result")
print("The result is:", result)


apply_callback(5, print_result)

Output:

Python callback function

Callback using built-in functions

sorted(iterable, key)
  • iterable: A data structure that is to be sorted (List, dictionary, etc.)
  • key (keyword, optional): Criteria for sorting. It can be assigned any function that you want to use.

Sort a list of strings

#list
a = ["lmn", "AbCd", "khJH", "ert", "SuNnY"]
 
#sorted based on the ASCII values
print(sorted(a))
 
#first convert all letters to lowercase & then sort based on ASCII values
print(sorted(a, key=str.lower))

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading