pythonlist-comprehensionself-reference

How to refer to itself in the list comprehension?


list_a = [2, 4, 3, 6, 3, 8, 5]

list comprehension is very useful.

list_b = [a**2 for a in list_a]

I want to know how to write a self-reference in the list comprehension.

For example:

list_c = [a**2 if i == 0 else a*2 + (itself[i-1]) for i, a in enumurate(list_a)]

how to write the part of itself[i-1]?


Solution

  • List comprehension is meant to be a compact expression for the most straightforward use cases. You cannot reference the list itself in list comprehension, for that just use a regular for-loop:

    list_c = []
    for i, a in enumerate(list_a):
        if i == 0:
            list_c.append(a ** 2)
        else:
            list_c.append(a * 2 + list_c[i-1])
    

    You can also rewrite that loop in a more efficient way:

    list_a_iterator = iter(list_a)
    list_c = [next(list_a_iterator) ** 2]  # May raise StopIteration if list_a is empty
    for item in list_a_iterator:
        list_c.append(item * 2 + list_c[-1])