pythonlist-comprehension

Multiple statements in list compherensions in Python?


Is it possible to have something like:

list1 = ...

currentValue = 0
list2 = [currentValue += i, i for i in list1]

I tried that but didn't work? What's the proper syntax to write those?

EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.


Solution

  • 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! :-)