扩展列表返回无 [英] Extending list returns None

查看:60
本文介绍了扩展列表返回无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add a string to a list:

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

,但它打印None.为什么会这样?

but it prints None. Why is that?

推荐答案

函数 extend 是一个就位函数,即它将对原始列表本身进行更改.来自文档

The function extend is an in-place function i.e. It will make the changes to the original list itself. From the docs

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

Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

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

Hence you do not need to re-assign it back to the list variable.

您可以

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

然后当您print list它将打印

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

更好的方式

Better way

使用下面提到的append是更好的方法.

Using append as mentioned below is the better way to do it.

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

这篇关于扩展列表返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆