小编典典

扩展列表返回None

python

我想将一个字符串添加到列表中:

list1 = ['hi','how','are','you','googl']
ok = 'item22'
list1 = list1.extend(ok)

但它打印None。这是为什么?


阅读 164

收藏
2020-12-20

共1个答案

小编典典

该函数extend是就地函数,即它将对原始列表本身进行更改。来自文档

通过添加 给定 列表中的所有项目来扩展列表;等效于a [len(a):] =L。

因此,您无需将其重新分配回列表变量。

你可以做

list1 = ['hi','how','are','you','googl']
ok = 'item22'
list1.extend([ok])   # Notice brackets here

然后当您print list打印时

['hi','how','are','you','googl','item22']

更好的方法

append如下所述使用是更好的方法。

list1 = ['hi','how','are','you','googl']
ok = 'item22'
list1.append(ok)   # Notice No brackets here
2020-12-20