How to clear a list in Python? 4 ways to clear a list (code example)

青灯夜游
Release: 2019-03-22 13:29:48
Original
39401 people have browsed it

There are many ways to clear the list through different construction methods provided by the Python language. The following article will introduce you to 4 methods of clearing the list in Python. I hope it will be helpful to you.

How to clear a list in Python? 4 ways to clear a list (code example)

Method 1: Reinitialize the list

You can reinitialize the list and initialize the items in the scope When using a list, the list will be initialized without a value, allowing the list to be cleared.

Code example:

List = [5, 6, 7] 
print('List清空前:', List)  
#重新初始化列表
List = [] 
print('List清空后:', List)
Copy after login

Output:

How to clear a list in Python? 4 ways to clear a list (code example)

##Method 2: Use the clear() method

clear() method is used to clear the list. Basic syntax:


list.clear()
Copy after login

Code example:

List = [6, 0, 4, 1] 
print('List清空前:', List)  
  
#清空元素
List.clear()  
print('List清空后:', List)
Copy after login

Output:


How to clear a list in Python? 4 ways to clear a list (code example)

Method 3: Use "* = 0"

This is a little-known method, but This method removes all elements from the list and makes them empty.

Code example:

List = [8, 6, 16] 
print ("List清空前 : " + str(List)) 
#重新初始化列表
List *= 0
print("List清空后:" + str(List))
Copy after login

Output:


How to clear a list in Python? 4 ways to clear a list (code example)

##Method 4: Use del a[: ] del can be used to clear list elements in the range. If we do not give a range, all elements will be deleted to clear the list.

Code example

List1 = [8, 6, 16] 
List2 = [4, 5, 7] 

print ("List1清空前 : " + str(List1)) 
#使用del删除List1
del List1[:] 
print("List1清空后:" + str(List1))  

print('\n') 
 
print ("List2清空前 : " + str(List2)) 
#使用del删除List2
del List2[:] 
print("List2清空后:" + str(List2))
Copy after login

Output:


How to clear a list in Python? 4 ways to clear a list (code example)Related video tutorial recommendation: "

Python3 Tutorial

" The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to clear a list in Python? 4 ways to clear a list (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template