Search code examples
pythonlisttuplesextend

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?


Solution

  • 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]