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

4 Answers

0 votes
# Using list Comprehension (most Pythonic)

# Define a simple function that squares a number (callback function)
def square(x):
    return x * x

# The input list
lst = [1, 2, 3, 4]

# Apply the function to each element using a list comprehension
# This loops over lst and builds a new list with square(x) for each x
result = [square(x) for x in lst]

print(result) 


'''
run:
 
[1, 4, 9, 16]
 
'''

 



answered Mar 19 by avibootz
edited Mar 19 by avibootz
0 votes
# Using map() (functional style)

# Define the callback function
def square(x):
    return x * x

# Input list
lst = [1, 2, 3, 4]

# map(square, lst) applies square() to each element
# Wrapping with list() converts the map object into a list
result = list(map(square, lst))

print(result)  


'''
run:
 
[1, 4, 9, 16]
 
'''

 



answered Mar 19 by avibootz
0 votes
# Using for-loop 

# Define the callback function
def square(x):
    return x * x

# Input list
lst = [1, 2, 3, 4]

# Create an empty list to store results
result = []

# Loop through each element and apply the function manually
for x in lst:
    result.append(square(x))  # Add the squared value to result

print(result) 


'''
run:
 
[1, 4, 9, 16]
 
'''

 



answered Mar 19 by avibootz
0 votes
# Using a lambda (inline anonymous function)

# Input list
lst = [1, 2, 3, 4]

# Use map() with a lambda function instead of defining square()
# lambda x: x * x is an anonymous function that returns x squared
result = list(map(lambda x: x * x, lst))

print(result)  # Output: [1, 4, 9, 16]



'''
run:
 
[1, 4, 9, 16]
 
'''

 



answered Mar 19 by avibootz
...