Open In App

Different ways to clear a list in Python

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, let’s discuss different ways to clear a list in Python. Python provides a lot of different ways to clear a list and we will discuss them in this article.

Example

Input: [2, 3, 5, 6, 7]
Output: []
Explanation: Python list is cleared and it becomes empty so we have returned empty list.

Different Ways to Remove from a List in Python

There are many ways of clearing the list through methods of different constructs offered by Python language. Let’s try to understand each of the methods one by one.

  • Using clear()
  • Reinitializing the list
  • Using “*= 0”
  • Using del
  • Using pop() method
  • Using slicing
  • using list comprehension

Clear a List using Python List clear()

In this example, we are using clear() method to clear a list in Python.

Python3
GEEK = [6, 0, 4, 1]
print('GEEK before clear:', GEEK)

# Clearing list
GEEK.clear()
print('GEEK after clear:', GEEK)

Output
GEEK before clear: [6, 0, 4, 1]
GEEK after clear: []

Clear a List by Reinitializing the List

The initialization of the list in that scope initializes the list with no value. i.e list of size 0. Let’s see the example demonstrating Method 1 and 2 to clear list. 

Python3
list1 = [1, 2, 3]

# Printing list2 before deleting
print("List1 before deleting is : "
      + str(list1))

# deleting list using reinitialization
list1 = []

# Printing list2 after reinitialization
print("List1 after clearing using reinitialization : "
      + str(list1))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using reinitialization : []

Clearing a Python List Using “*= 0”

This is a lesser-known method, but this method removes all elements of the list and makes it empty. In this example, we are using *=0 to clear a list.

Python3
# Initializing lists
list1 = [1, 2, 3]

# Printing list2 before deleting
print("List1 before clearing is : "
      + str(list1))

list1*=0
# Printing list2 after reinitialization
print("List1 after clearing using *=0 : "
      + str(list1))

Output
List1 before clearing is : [1, 2, 3]
List1 after clearing using *=0 : []

Clearing a List Using del

Python del can be used to clear the list elements in a range, if we don’t give a range, all the elements are deleted. In this example, we are using del keyword to clear a list.

Python3
list1 = [1, 2, 3]
list2 = [5, 6, 7]

# Printing list1 before deleting
print("List1 before deleting is : " + str(list1))

# deleting list1 using del
del list1[:]
print("List1 after clearing using del : " + str(list1))


# Printing list2 before deleting
print("List2 before deleting is : " + str(list2))

# deleting list using del
del list2[:]
print("List2 after clearing using del : " + str(list2))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using del : []
List2 before deleting is : [5, 6, 7]
List2 after clearing using del : []

Python pop() method To Clear a List

In this example, we are using pop() method to clear a list.

Python3
list1 = [1, 2, 3]

# Printing list1 before deleting
print("List1 before deleting is : " + str(list1))

# deleting list1
while(len(list1) != 0):
    list1.pop()
print("List1 after clearing using del : " + str(list1))

Output
List1 before deleting is : [1, 2, 3]
List1 after clearing using del : []

Time Complexity: O(n^2) where n is the length of the list list1.
Auxiliary Space: O(1).

Clear a List using Slicing

This method involves using slicing to create a new list with no elements, and then assigning it to the original list variable. In this example, we are using slicing to clear a list.

Python3
# Initializing list
lst = [1, 2, 3, 4, 5]

print("List before clearing: ",lst)
# Clearing list using slicing
lst = lst[:0]
print("List after clearing using Slicing: ",lst)

Output
List before clearing:  [1, 2, 3, 4, 5]
List after clearing using Slicing:  []

Time Complexity: O(1)
Auxiliary Space: O(n), where n is length of list.

Clear a list using list comprehension method

The clear_list function is designed to clear or empty the input list, lst, by comprehensively filtering its elements through a list comprehension that always evaluates to False. Here’s a simplified explanation based on your example:

  1. Function Definition: clear_list(lst) takes a list lst as its parameter.
  2. List Comprehension: Inside the function, a new list is created with a list comprehension [item for item in lst if False]. Because the condition is always False, no elements from the original list lst satisfy the condition, resulting in an empty list.
  3. Return Empty List: The function returns this newly created empty list.
  4. Testing the Function: input_list is defined with elements [2, 3, 5, 6, 7]. When clear_list is called with input_list, it returns an empty list [].
  5. Print Output: The output, which is an empty list, is printed, showing [].
Python
def clear_list(lst):
    lst = [item for item in lst if False]
    return lst

input_list = [2, 3, 5, 6, 7]
output = clear_list(input_list)
print(output)  # Output: []

Output
[]

Time complexity:O(n)

auxiliary space:O(n), where n is length of list.




Previous Article
Next Article

Similar Reads

PyQt5 – How to clear the content of label | clear and setText method
In this article, we will see how we can easily clear/erase the content of the label of PyQt5 application. This can be done in two ways - Using clear() method, this will clear the content of the label. Using setText() method with passing a blank string, this will update the content with blank string. Using clear() method - Syntax : label.clear() Arg
2 min read
Python | Ways to split a string in different ways
The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples: Input : Paras_Jain_Moengage_best Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage',
2 min read
Extending a list in Python (5 different ways)
In this article, we are going to learn different methods of extending a list in Python. The list is the widely used Python data structure and it can be extended by adding elements to the list. There are various methods to extend the list in Python which includes using an inbuilt function such as append(), chain() and extend() function and using the
3 min read
Python List clear() Method
Python List clear() method removes all items from the List making it an empty/null list. Example C/C++ Code lis.clear() print(lis) Output[] What is List clear() Method?list clear() is an in-built function in Python, that is used to delete every element from a list. It can make any list into a null list and should be used with caution. It is one of
4 min read
How to apply different titles for each different subplots using Plotly in Python?
Prerequisites: Python Plotly In this article, we will explore how to apply different titles for each different subplot. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a sufficient amount of information about data when pointing the cursor over the point label appears. It provides us
2 min read
Python | Different ways to kill a Thread
In general, killing threads abruptly is considered a bad programming practice. Killing a thread abruptly might leave a critical resource that must be closed properly, open. But you might want to kill a thread once some specific time period has passed or some interrupt has been generated. There are the various methods by which you can kill a thread
8 min read
Different ways to Invert the Binary bits in Python
We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value). Sometimes it is required to inverse the bits i.e., 0's to 1's ( zeros to ones) and 1's to 0's (ones to zeros). Here are there few ways by which we can inverse the bits in Python. 1) Using Loops: By iterating each and every bit w
3 min read
Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs of t
3 min read
Reverse string in Python (6 different ways)
Python string library doesn't support the in-built "reverse()" as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it in Python. Example: Input: GeeksforgeeksOutput: skeegrofskeeGReverse a string in Python using a loopIn this example, we c
5 min read
Different Ways of Using Inline if in Python
Python offers a concise and expressive way to handle conditional logic in your code by using inline if. Whether you need an essential conditional expression or want to nest multiple conditions, inline can make your code more readable and maintainable. Among these tools is the inline if statement, an invaluable asset for crafting short, yet intuitiv
3 min read