How can I call a function to each item in a list. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can I call a function to each item in a list.

I tried for i in (name of the list) NewListName = list(functionName(i)) This caused type error : int object is not iterable

18th Jan 2020, 5:09 PM
ravindu poorna
ravindu poorna - avatar
2 Answers
+ 4
The map function allows you to perform a function for each element in an iterable. The syntax is map(function, iterable). This returns a map object, which you can turn into a list. In your case, you can do: new_list = list(map(functionName, name_of_list)) Here, new_list is a list containing the returned value of the function for each element in your list. For the error, where did it occur? The error could have been raised if the name of the list you were using in your for loop was actually an integer, but it could also have been caused by something from within the function you called.
18th Jan 2020, 5:33 PM
Zerokles
Zerokles - avatar
+ 1
Thank you everyone.. using maps succeeded
18th Jan 2020, 6:20 PM
ravindu poorna
ravindu poorna - avatar