Python append()函数

描述

append函数可以在列表的末尾添加新的对象。函数无返回值,但是会修改列表。

语法

list.append(object)
名称 说明 备注
list 待添加元素的列表  
object 将要给列表中添加的对象 不可省略的参数

举例

1. 给列表中添加整数、浮点数和字符串:

test = ['Python', 'C', 'Java']

test.append(5)
test.append(23.6)
test.append('HTML')

print(test)

输出结果为:

['Python', 'C', 'Java', 5, 23.6, 'HTML']

2. 给列表中添加列表、元组和字典:

test = ['Python', 'C', 'Java']

test.append(['Windows', 2018, 'OpenStack'])
test.append(('Huawei', 'Tencent'))
test.append({'Nova':'virtual compute service', 'Neutron':'net service'})

print(test)

输出结果为:

['Python', 'C', 'Java', ['Windows', 2018, 'OpenStack'], ('Huawei', 'Tencent'), {'Nova': 'virtual compute service', 'Neutron': 'net service'}]

3. 给列表中添加空元素

test = ['Python', 'C', 'Java']

test.append(None)

print(test)

输出结果为:

['Python', 'C', 'Java', None]

注意事项

object参数不能省略,否则Python会报错:

test = ['Python', 'C', 'Java']

test.append()

print(test)
Traceback (most recent call last):
  File "/Users/untitled3/Test2.py", line 3, in <module>
    test.append()
TypeError: append() takes exactly one argument (0 given)

如果想给列表末尾添加空元素,应该将参数写为None

猜你喜欢

转载自blog.csdn.net/TCatTime/article/details/82555430