参考:https://stackoverflow.com/questions/49043101/how-does-list-1-work-in-python
List型に+=1,すると動くが、これはどのような動きなのかという疑問。
ちなみに、他の書き方を試してみる。
>>> lis = [1] >>> lis = lis + 1 #intは連結できない Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "int") to list >>> lis = lis + (1,) #タプルは連結できない Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "tuple") to list >>> lis += 1 #intはイテラブルではない Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
結果的にlis += 1, というのは__iadd__()が内部で呼ばれる。
__iadd__()はインプレース算術演算子で、演算子+=のこと。