Search code examples
pythonlist-comprehensionvariable-assignment

How would I modify an outside variable within a list comprehension?


Python code:

i: int = 1
table: list = [[i, bit, None, None] for bit in h]

Expected behaviour: i needs to be incremented by 1 per iteration.

Pseudocode:

i: int = 1
table: list = [[i++, bit, None, None] for bit in h]

Solution

  • List comprehensions shouldn't be used for outside side-effects. In this case, use enumerate instead of an outside variable:

    h = '10010010'  # Undefined in OP example.  Just something to enumerate.
    table = [[i, bit, None, None ] for i, bit in enumerate(h, start=1)]
    for row in table:
        print(row)
    

    Output:

    [1, '1', None, None]
    [2, '0', None, None]
    [3, '0', None, None]
    [4, '1', None, None]
    [5, '0', None, None]
    [6, '0', None, None]
    [7, '1', None, None]
    [8, '0', None, None]