3

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
newValues = []

for value in my_list:
    x = x + 1
    newValues.append(myCoolFunction(value))
    print(x)

I am working with around 125,000 values and the speed at which this is operating does not seem very efficient.

Is there a more pythonic way to apply the function to the values?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Learning Developer
  • 156
  • 2
  • 4
  • 14
  • 2
    A _list comprehension_: `new_values = [myCoolFunction(value) for value in my_list]`. Drop the camel-case on variable names too, it isn't part of [PEP8](https://www.python.org/dev/peps/pep-0008/#naming-conventions) – roganjosh Apr 06 '19 at 13:38
  • Does this answer your question? [Apply function to each element of a list](https://stackoverflow.com/questions/25082410/apply-function-to-each-element-of-a-list) – mkrieger1 Feb 03 '23 at 13:00

2 Answers2

9

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.

Austin
  • 25,759
  • 4
  • 25
  • 48
2

In case you are using pandas, 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)

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Rich Andrews
  • 1,590
  • 8
  • 12