AttributeError: 'tuple' object has no attribute 'extend'

出错demo



 In [5]: a.extend([4,5])
 ---------------------------------------------------------------------------
 AttributeError                            Traceback (most recent call last)



打印一下tuple类型的属性可以看到,tuple类型除内置类型外,只有count和index两个属性


extend是list类型的方法



 In [3]: dir(tuple)
 Out[3]:
 ['__add__',
  '__class__',
  '__contains__',
  '__delattr__',
  '__dir__',
  '__doc__',
  '__eq__',
  '__format__',
  '__ge__',
  '__getattribute__',
  '__getitem__',
  '__getnewargs__',
  '__gt__',
  '__hash__',
  '__init__',
  '__init_subclass__',
  '__iter__',
  '__le__',
  '__len__',
  '__lt__',
  '__mul__',
  '__ne__',
  '__new__',
  '__reduce__',
  '__reduce_ex__',
  '__repr__',
  '__rmul__',
  '__setattr__',
  '__sizeof__',
  '__str__',
  '__subclasshook__',
  'count',
  'index']



extend是1个列表+另一个列表,


它会改变原来列表的长度,而不会生成一个新的列表


所以,如果你使用了a=list.extend(XXX),它并不会如你希望 返回一个列表,而是一个None


示例 :



 In [6]: b=[1,2]                                                                 

 In [7]: c=b.extend([3])                                                         

 In [8]: b
 Out[8]: [1, 2, 3] 

 In [10]: print(c)
 None

 In [11]: type(c)
 Out[11]: NoneType



顺便说明一下:


count表示统计元组中指定的1个元素 出现的次数



 In [20]: b=(2,2,2,3,4)                                                          

 In [21]: b.count(2)
 Out[21]: 3



index返回指定元素第1次出现的位置(下标)



 In [20]: b=(2,2,2,3,4)                                                          

 In [22]: b.index(3)
 Out[22]: 3

 In [23]: b.index(2)
 Out[23]: 0



附:


list的所有属性如下



 In [4]: dir(list)
 Out[4]:
 ['__add__',
  '__class__',
  '__contains__',
  '__delattr__',
  '__delitem__',
  '__dir__',
  '__doc__',
  '__eq__',
  '__format__',
  '__ge__',
  '__getattribute__',
  '__getitem__',
  '__gt__',
  '__hash__',
  '__iadd__',
  '__imul__',
  '__init__',
  '__init_subclass__',
  '__iter__',
  '__le__',
  '__len__',
  '__lt__',
  '__mul__',
  '__ne__',
  '__new__',
  '__reduce__',
  '__reduce_ex__',
  '__repr__',
  '__reversed__',
  '__rmul__',
  '__setattr__',
  '__setitem__',
  '__sizeof__',
  '__str__',
  '__subclasshook__',
  'append',
  'clear',
  'copy',
  'count',
  'extend',
  'index',
  'insert',
  'pop',
  'remove',
  'reverse',
  'sort']