In Python, apart from defining a class to store the memory variables, you can use a closure to achieve the same.
def run(): count = 0 last_sign = 0 def sign(i): return 1 if i > 0 else -1 def f(i): nonlocal count nonlocal last_sign if sign(i) == last_sign: count = count+1 else: last_sign = sign(i) count = 1 return count return ff = run()y = [f(i) for i in x]
Note this works for Python 3 only (in Python 2 I think you cannot modify the closure variable like this). Similar thing for summation as well.