0

I encountered this python code somewhere:

p = {
        s: path.join(
            dir , s)
        for s in samples
    }

Can somebody please explain or point me to documentation on two puzzling aspects of this code?

  1. You can put the for-loop declaration statement (for s in samples) after the for-loop body in python?
  2. The for-loop body has the same indentation a the for-loop declaration statement (for s in samples)? I thought that the body of a for-loop was required to be indented with respect to the for-loop declaration statement?
cmo
  • 2,912
  • 3
  • 29
  • 56
  • 2
    The for loop is placed after because it's a dictionary comprehension (similar to list comprehension). The one-liner, 100% equivalent is `{s: path.join(dir, s) for s in samples}`. The weird indentation is possible because of the brackets and the position at which a line can be skipped. I don't really know how to explain this part, someone may have a good explanation. – Mathieu Apr 27 '21 at 12:12
  • 1
    @Mathieu Inside virtually any bracketed expression, indentation doesn't really matter. Python uses indentation to know what part of the code belongs where logically; that is pretty unambiguous within brackets. – deceze Apr 27 '21 at 12:14

0 Answers0