I am reading a snippet of Python code and there is one thing I can't understand. a
is a list, num
is an integer
a += num,
works but
a += num
won't work. Can anyone explain this to me?
A trailing comma, also known as a dangling or terminal comma, is a comma symbol that is typed after the last item of a list of elements. Since the introduction of the JavaScript language, trailing commas have been legal in array literals. Later, object literals joined arrays.
Trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to JavaScript code. If you want to add a new property, you can add a new line without modifying the previously last line if that line already uses a trailing comma.
To create a tuple with only one item, you have add a comma after the item, otherwise Python will not recognize the variable as a tuple.
In Python, lists are ordered collections of items that allow for easy use of a set of data. List values are placed in between square brackets [ ] , separated by commas. It is good practice to put a space between the comma and the next value.
First of all, it is important to note here that a += 1,
works differently than a = a + 1,
in this case. (a = a + 1,
and a = a + (1,)
are both throwing a TypeError
because you can't concatenate a list and a tuple, but you you can extend a list with a tuple.)
+=
calls the lists __iadd__
method, which calls list.extend
and then returns the original list itself.
1,
is a tuple of length one, so what you are doing is
>>> a = []
>>> a.extend((1,))
>>> a
[1]
which just looks weird because of the length one tuple. But it works just like extending a list with a tuple of any length:
>>> a.extend((2,3,4))
>>> a
[1, 2, 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With