Search code examples
pythonlistlist-comprehensioninternals

Are list comprehensions fully evaluated before being used in the rest of the code?


Consider the following code.

with open('filename.txt', 'r') as f:
    var = [element for element in f.readlines()][3]

This question concerns the internals of Python, rather than the result.

Does Python calculate all the elements of the indexes in the entire list of [element for element in f.readlines()], or does Python just calculate all of the elements until the third index?


Solution

  • It calculates all of them. You can verify with something like this:

    >>> [(i, print(i)) for i in range(3)][1]
    0
    1
    2
    (1, None)
    

    This isn't really "internal", because this is well-defined behaviour and list comprehensions can have side-effects (even if they shouldn't).