Skip to main content
Question Protected by Jamal
Tweeted twitter.com/StackCodeReview/status/807189257001594881
edited tags
Link
Peilonrayz
  • 44.6k
  • 7
  • 80
  • 158
Source Link
Natha
  • 347
  • 1
  • 2
  • 8

Pythonic way to add each previous element in list

It's a very simple question, but I wonder if there is a more pythonic way to add each previous elements in a list like this (for example with a list comprehension maybe) :

input : L = [4, 2, 1, 3] output : new_L = [4, 6, 7, 10] 

Which I've done this way :

def add_one_by_one(L): new_L = [] for elt in L: if len(new_L)>0: new_L.append(new_L[-1]+elt) else: new_L.append(elt) return new_L new_L = add_one_by_one(L)