Skip to content Skip to sidebar Skip to footer

Apply Function To All Items In A List Python

I am trying to apply a function to a list. The function takes a value and produces another. for example: myCoolFunction(75) would produce a new value So far I am using this: x = 0

Solution 1:

You can use map approach:

list(map(myCoolFunction, my_list))

This applies defined function on each value of my_list and creates a map object (3.x). Calling a list() on it creates a new list.

Solution 2:

This question is heavily tagged with Pandas related things. And so here is how the pythonic mapping and list comprehension techniques mentioned above are done with Pandas.

import pandas as pd

def myCoolFunction(i):
    return i+1

my_list = [1,2,3]
df = pd.DataFrame(index=my_list, data=my_list, columns=['newValue']).apply(myCoolFunction)

Post a Comment for "Apply Function To All Items In A List Python"