Skip to content

Instantly share code, notes, and snippets.

@mchung
Last active April 2, 2021 08:00
Show Gist options
  • Select an option

  • Save mchung/76d774879245b355e8bff95f9172f9f8 to your computer and use it in GitHub Desktop.

Select an option

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]
@tbhaxor
Copy link
Copy Markdown

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
Copy Markdown

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
Copy Markdown

Thx a lot ^)

@zengqingfu1442
Copy link
Copy Markdown

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