Skip to content

Instantly share code, notes, and snippets.

@mchung
Last active April 2, 2021 08:00
Show Gist options
  • Save mchung/76d774879245b355e8bff95f9172f9f8 to your computer and use it in GitHub Desktop.
Save mchung/76d774879245b355e8bff95f9172f9f8 to your computer and use it in GitHub Desktop.
Example of callbacks with Python
# 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]
@Neverik
Copy link

Neverik commented Mar 31, 2018

Can't you just use map() in the add() function?

@tbhaxor
Copy link

tbhaxor commented Mar 26, 2019

Can't you just use map() in the add() function?

Then first parameter will work as callback

Same code using map

def add2(number):
    return number + 2

def mul2(number):
    return number * 2

print(list(map(add2, [1, 2, 3, 4]))) # [3, 4, 5, 6]
print(list(map(mul2, [1, 2, 3, 4]))) # [2, 4, 6, 8]

@Rajan-sust
Copy link

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]

@YuriiSmolii
Copy link

Thx a lot ^)

@zengqingfu1442
Copy link

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