Is the behaviour of Python's list += iterable documented anywhere?

前端 未结 4 1627
鱼传尺愫
鱼传尺愫 2020-11-29 09:21

It would appear that in Python, list += x works for any iterable x:

In [6]: l = []

In [7]: l += [1]

In [8]: l += (2, 3)

In [9]:          


        
4条回答
  •  旧巷少年郎
    2020-11-29 09:32

    It is now documented in Python 3.4+ and Python 2.7:

    4.6.3. Mutable Sequence Types

    The operations in the following table are defined on mutable sequence types. The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.

    [Below] s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s (for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).


    s.extend(t) or s += t

    extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)

    So it is now documented that for any mutable sequence type s, s += t is synonymous with s.extend(t).

提交回复
热议问题