Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a += number and a += number, (with a trailing comma) when a is a list?

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?

like image 501
yuhengd Avatar asked Apr 09 '17 20:04

yuhengd


People also ask

What does trailing comma mean?

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.

Should we use trailing commas?

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.

Why does a tuple with one element need a 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.

Does a list need commas in Python?

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.


1 Answers

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]
like image 161
timgeb Avatar answered Oct 03 '22 20:10

timgeb