How to apply a callback to a list (apply a function to each element) in Python

3 Answers

0 votes
# Using Python’s built‑in map()

# map() is designed to apply a function to each element

def double(x):
    return x * 2

numbers = [5, 10, 15, 20]

doubled = list(map(double, numbers))

print(doubled)



'''
run:

[10, 20, 30, 40]

'''

 



answered Mar 21 by avibootz
0 votes
# Using a lambda callback (inline function)
 
numbers = [5, 10, 15, 20]
 
tripled = list(map(lambda x: x * 3, numbers))
 
print(tripled)
 
 
 
'''
run:
 
[15, 30, 45, 60]
 
'''

 



answered Mar 21 by avibootz
0 votes
# List comprehension (the most Pythonic)

numbers = [5, 10, 15, 20]

doubled = [x * 2 for x in numbers]

print(doubled)



'''
run:

[10, 20, 30, 40]

'''

 



answered Mar 21 by avibootz
...