0
with open(path, "w", encoding="utf-8") as outfile:
        [outfile.write(d + "\n") for d in data]

I don't understand the use of the square brackets in this statement. From my understanding, this will create a new list, and when I delete the square brackets, I get the error:

  File "test.py", line 6
    outfile.write(d + "\n") for d in data
                              ^
SyntaxError: invalid syntax

How to understand the "[]" in this code. Thanks in advance.

Max Be
  • 97
  • 8
  • 2
    The grammar of a list comprehension (first code snippet) is just defined differently by Python from the grammar of an ordinary for-loop. – Michael Butscher May 19 '21 at 03:28
  • 2
    In this instance, the square brackets denote a [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). It is not illegal but I wouldn't use a list comprehension here because it seems to obscure rather than simplify the code. – Nicholas Hunter May 19 '21 at 03:32
  • @NicholasHunter So instead of creating a new list, it just does some operations on each item in the list, and in this case, outputs a new line. Can I understand in this way? – Max Be May 19 '21 at 03:36
  • Yes, that's what it's doing. Normally one would use a list comprehension to create a list like so `results = [outfile.write(d + "\n") for d in data]`. If you did that here, you would get a list of the return values of each call to outfile.write. Since outfile.write has no return value, I guess you would get a list of Nones. – Nicholas Hunter May 19 '21 at 03:42

0 Answers0