Is it possible to have something like:
list1 = ...
currentValue = 0
list2 = [currentValue += i, i for i in list1]
I tried that but didn\'t wor
Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:
def total_and_item(sequence):
total = 0
for i in sequence:
total += i
yield (total, i)
list2 = list(total_and_item(list1))
The generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)