Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a function (not a built in function) inside a list comprehension in python?

Say we have a list:

X = [1,2,3,4,5,6,7,8]

and we have created a function called add():

def add():
  sum = 0
  result = 0
  for e in X:
    sum = sum + e
    return sum
add()

which runs through a list of numbers X, adding the next element in the list to the previous sum. So for each element X[i], we have:

1
3
6
10
15
21
28
36
45

Now, what if I want to put these results in a list again, by making use of a list comprehension. Is it possible to call a function such as add() within a list comprehension, given that it is possible to apply built in functions inside list comprehensions?

I have tried the following:

L = [add() for e in X]
print L

which gives

[None, None, None, None, None, None, None, None, None]

instead of

[1,3,6,10,15,21,28,36,45]

Why am I getting NoneType values in this list?

like image 756
Seraphina Avatar asked Mar 16 '26 12:03

Seraphina


2 Answers

You could do this with yield to keep with your original format:

    X = [1,2,3,4,5,6,7,8]

    def add():
      sum = 0
      for e in X:
        sum = sum + e
        yield sum

    L = [value for value in add()]
    print L
like image 69
klasske Avatar answered Mar 18 '26 01:03

klasske


Yes, it is possible to call functions inside list comprehensions. Your example is fine - it's the add() function that is to be blamed. What you need is make the add() function receive an argument - the list to sum.

def add(elements):
    sum = 0
    for el in elements:
        sum += el
    return sum

This way, the list comprehension would look like this:

L = [add(X[:i+1]) for i in xrange(len(X))]
[1, 3, 6, 10, 15, 21, 28, 36]

This is equivalent to:

L = [add(X[:1]), add(X[:2]), ..., add(X[:8])]

Which turns out to be a list of prefix sums - the thing you want.

like image 35
Maciej Gol Avatar answered Mar 18 '26 00:03

Maciej Gol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!