Appending a range to a list

假如想象 提交于 2019-12-06 05:27:41
Martijn Pieters

You appended a single list object. You did not add the elements from the list that range produces to L. A nested list object adds just one more element:

>>> L = ['a', 'bb', 'ccc']
>>> L.append(range(2))
>>> L
['a', 'bb', 'ccc', [0, 1]]

Note the [0, 1], the output of the range() function.

You are looking for list.extend() instead:

>>> L = ['a', 'bb', 'ccc']
>>> L.extend(range(2))
>>> L
['a', 'bb', 'ccc', 0, 1]
>>> len(L)
5

As an alternative to list.extend(), in most circumstances you can use += augmented assignment too (but take into account the updated L list is assigned back to L, which can lead to surprises when L was a class attribute):

>>> L = ['a', 'bb', 'ccc']
>>> L += range(2)
>>> L
['a', 'bb', 'ccc', 0, 1]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!