当前位置:Gxlcms > Python > python中怎么将列表的数据清空

python中怎么将列表的数据清空

时间:2021-07-01 10:21:17 帮助过:66人阅读

python中将列表数据清空的方法:1、使用del关键字,语法格式“del list[:]”;2、使用clear()方法,该方法用于从列表中删除所有元素,语法格式“list.clear()”。

本教程操作环境:windows7系统、python3版,DELL G3电脑

python中将列表数据清空的方法

1、使用del关键字

del可以用来清除范围中的列表元素,如果我们不给出范围,则删除所有元素,做到清空列表。

  1. #!/usr/bin/python
  2. List1 = [8, 6, 16]
  3. List2 = [4, 5, 7]
  4. print ("List1清空前 : " + str(List1))
  5. #使用del删除List1
  6. del List1[:]
  7. print("List1清空后:" + str(List1))
  8. print('\n')
  9. print ("List2清空前 : " + str(List2))
  10. #使用del删除List2
  11. del List2[:]
  12. print("List2清空后:" + str(List2))

输出:

  1. List1清空前 : [8, 6, 16]
  2. List1清空后:[]
  3. List2清空前 : [4, 5, 7]
  4. List2清空后:[]

2、使用clear()方法

clear() 方法从列表中删除所有元素。

语法

  1. list.clear()

代码示例:

  1. #!/usr/bin/python
  2. List = [6, 0, 4, 1]
  3. print('List清空前:', List)
  4. #清空元素
  5. List.clear()
  6. print('List清空后:', List)

输出:

  1. List清空前: [6, 0, 4, 1]
  2. List清空后: []

相关推荐:Python3视频教程

以上就是python中怎么将列表的数据清空的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行