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:
- Passing one function as an argument to another function
- 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
res = value * 2
print("The result is:", result)
Callback using built-in functions
- 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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.