In this tutorial, we will learn how to clear a list in Python. Clearing a list is useful when you want to remove all elements from a list, making it an empty list. Python provides several ways to achieve this, and we will be discussing four methods: the del keyword, the clear() function, the * operator, and using list slicing.
Method 1: Using the del keyword
The del keyword is used to delete a list or a part of the list. It can also be used to delete elements from a list. Use the following syntax to delete the entire list:
1 |
del list[:] |
Here’s an example:
1 2 3 |
fruits = ['apple', 'banana', 'orange'] del fruits[:] print(fruits) |
[]
As you can see, the list is now empty.
Method 2: Using the clear() function
The clear() function is another way to clear a list in Python. It removes all elements from the list. The syntax is as follows:
1 |
list.clear() |
Here’s an example:
1 2 3 |
fruits = ['apple', 'banana', 'orange'] fruits.clear() print(fruits) |
[]
The list has been cleared successfully using the clear() function.
Method 3: Using the * operator
In Python, the * operator can be used to create a new list by repeating an existing one. To clear a list, simply multiply the original list by 0, like this:
1 |
list = list * 0 |
Here’s an example:
1 2 3 |
fruits = ['apple', 'banana', 'orange'] fruits = fruits * 0 print(fruits) |
[]
The list is now empty.
Method 4: Using list slicing
List slicing is another method to clear a list in Python. The syntax for list slicing is as follows:
1 |
list[:] = [] |
Here’s an example:
1 2 3 |
fruits = ['apple', 'banana', 'orange'] fruits[:] = [] print(fruits) |
[]
The list has been successfully cleared using list slicing.
Full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Method 1 fruits = ['apple', 'banana', 'orange'] del fruits[:] print(fruits) # Method 2 fruits = ['apple', 'banana', 'orange'] fruits.clear() print(fruits) # Method 3 fruits = ['apple', 'banana', 'orange'] fruits = fruits * 0 print(fruits) # Method 4 fruits = ['apple', 'banana', 'orange'] fruits[:] = [] print(fruits) |
Conclusion
In this tutorial, we explored four ways to clear a list in Python: using the del keyword, the clear() function, the * operator, and list slicing. All of these methods have their own advantages, and you can choose any of them based on your preferences. Now you are ready to clear lists efficiently in your Python programs.