Last active
April 2, 2021 08:00
-
-
Save mchung/76d774879245b355e8bff95f9172f9f8 to your computer and use it in GitHub Desktop.
Example of callbacks with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example of using callbacks with Python | |
# | |
# To run this code | |
# 1. Copy the content into a file called `callback.py` | |
# 2. Open Terminal and type: `python /path/to/callback.py` | |
# 3. Enter | |
def add(numbers, callback): | |
results = [] | |
for i in numbers: | |
results.append(callback(i)) | |
return results | |
def add2(number): | |
return number + 2 | |
def mul2(number): | |
return number * 2 | |
print add([1,2,3,4], add2) #=> [3, 4, 5, 6] | |
print add([1,2,3,4], mul2) #=> [2, 4, 6, 8] | |
Short version:
print(list(map(lambda x: x + 2, [1, 2, 3, 4]))) # [3, 4, 5, 6]
print(list(map(lambda x: x * 2, [1, 2, 3, 4]))) # [2, 4, 6, 8]
Thx a lot ^)
Thanks a lot. I am learning callback function.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Then first parameter will work as callback
Same code using map