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
  • 62,466
  • 11
  • 102
  • 153
smlee
  • 131
  • 1
  • 9

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
  • 28,235
  • 9
  • 60
  • 81