Using list comprehension to calculate the sum of all list elements

Viewed 255

Don't know if I'm just being stupid right now but I'm trying to convert a list of int to one int. The problem is that I am trying to do it with just a list comprehension but I'm failing every time

class MathStuff():
def add_stuff(self, *stuff):
    items = 0
    numbers = (i for i in stuff)
    items += [i for i in e]
#trying to do "for i in (i for i in stuff)" but assign it to a variable

I've tried multiple ways to do this without a "for loop" but I'm hitting a brick wall with my google searching.

2 Answers

If you have a list of numbers, l, and you don't want to use sum. I suppose you could do the usual:

l = range(1, 100)

s = 0
for i in l:
  s += i

Or a more functional approach.

from operator import add
from functools import reduce

l = range(1, 100)

reduce(add, l)

I don't see how comprehensions could help you solve this however.

If you really want to use list comprehension, you can make a new list with an equal number of list entries as your input data. Then, flatten the list, and finally, use its length as the sum. You have to do this for positive and negative values separately, though:

long_pos = [[i for i in range(l)] for l in stuff if l > 0]
long_neg = [[i for i in range(abs(l))] for l in stuff if l < 0]
flat_pos = [i for sub in long_pos for i in sub]
flat_neg = [i for sub in long_neg for i in sub]
items = len(flat_pos) - len(flat_neg)
Related