0

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?

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
smlee
  • 131
  • 7

1 Answers1

3

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).

wjandrea
  • 23,210
  • 7
  • 49
  • 68