The —alleged — Square Brackets Mistery of writerow()

I learnt of csv files and the csv module with the csv.writer class and the csv.writer.writerow() method and I was confused by something I was told by chatgtp.

It said that I need to use square brackets withing the writerow() method.

Like this:

csv.writer.writerow([value1,value2,value3])

I do not understand the reason behind creating this method to accept arguments in this square brackets form.

What difference does it make for the method to accept arguments this way?

csv.writer.writerow takes a single argument that is an iterable of the values to write

The square brackets in your example is just making a list from each of the values and passing that

It might be more clear to see it like this

values = [value1,value2,value3]
csv.writer.writerow(values)

When in doubt, consult the documentation.

In the documentation for writer objects we can read:

csvwriter.writerow(row )

Write the row parameter to the writer’s file object, formatted according to the current Dialect. Return the return value of the call to the write method of the underlying file object.

So the writerow method accepts just one parameter, row. But you want to write more values in one row. How?

That is in the description of the row:

A row must be an iterable of strings or numbers for writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects.

The brackets make the values into one variable of type list, which is an iterable as required. Other data types can be iterable too, but list is a simple, often used iterable.

1 Like

The writerow() method takes a single iterable argument. At least
since Python 3.5, any iterable type will do:

Your example is of passing a list. In Python, lists are indicated by
wrapping a sequence in square brackets. You could similarly pass a
tuple, which you would do by wrapping your sequence in (additional)
parentheses instead of square brackets. For literal values there’s
not much difference between lists and tuples, but if you plan to
have your program make in-place modifications to a sequence then you
likely want to use a list because tuples are immutable.

If you didn’t wrap your sequence of values in anything, Python would
see that as you trying to pass multiple arguments to the writerow()
method, and generate an error because it expects there to be only a
single argument.