What is the difference between the number + = and the number + = (with a final comma) when a is a list?

I am reading a snippet of Python code, and there is one thing that I cannot understand. a is a list, num is an integer

 a += num, 

works but

 a += num 

will not work. Can someone explain this to me?

+5
source share
3 answers

First of all, it is important to note here that in this case a += 1, works differently than a = a + 1, ,. ( a = a + 1, and a = a + (1,) throw a TypeError because you cannot concatenate the list and tuple, but you can expand the list with a tuple.)

+= calls the __iadd__ list, which calls list.extend , and then returns the original list.

1, is a tuple of length one, so what do you do

 >>> a = [] >>> a.extend((1,)) >>> a [1] 

which looks just weird because of the length of one tuple. But it works the same as expanding a list with a tuple of any length:

 >>> a.extend((2,3,4)) >>> a [1, 2, 3, 4] 
+4
source

The back comma makes the right-hand side of the destination a tuple, not an integer. A tuple is a container structure similar to a list (with some differences). For example, these two equivalents:

 a += num, a += (num, ) 

Python allows you to add a tuple to a list and add each element of the tuple to the list. This does not allow you to add a single integer to the list, for this you need to use append.

+3
source

using

 num, 

declares a tuple of length one, not an integer.

Thus, if a = [0,1] and num = 2

 a+=num, 

equivalently

 a.extend((num,)) 

or

 a.extend((2,))=[0,1,2] 

a

 a+=num 

equivalently

 a.extend(num) 

or

 a.extend(2) 

which gives an error because you can add a tuple to the array, but not an integer. So the first wording works, and the second gives you an error

+2
source

Source: https://habr.com/ru/post/1266527/


All Articles