List Clear Method in Python

From this tutorial, you will be learning about Python list Clear method. You will see how to apply it on sequences with the help of examples.

Note: The syntax used in the below section is for Python 3. You can change it to any other versions of Python.

Python List Clear

To Learn about Lists – Read Python List

List Clear Method

The clear() method performs the remove operation on a list and removes all the elements. Its syntax is as follows:

List_name.clear()

After the clear() method gets called, you will get an empty list object. It doesn’t return any value.

How does the Clear() function work?

There are other ways also that we can use to clear a list in Python. But the Clear method provides a simple way to perform the cleanup.

It doesn’t accept any argument and clears the entire list. After the operation, the list gets initialized to an empty object.

The flowchart for the mechanism is as follows:

Python List Clear Method Flowchart

Del Method to clear the list

We can achieve the same objective using Python’s del method. Try the following syntax.

del List_name[:]

See this example.

# Initialize a list
listtoclear = [{'a', 'x'}, (1), [3.5, (1, 2)]]

# clearing the list
del listtoclear[:]

print('List after clear():', listtoclear)

Below is the output after executing the above code.

List after clear(): []

You can see that the clear() method has better semantics than the del and a bit easy to use also.

List Clear() Method Examples

Clear a list containing numbers:

Fibonacci = [0, 1, 1, 2, 3, 5, 8]

Fibonacci.clear()

print (Fibonacci)

Output:

[]

Clear a list containing strings:

Linux_distro = ["Ubuntu OS", "Linux Mate OS", "Elementary OS", "Debian OS", "Kali Linux OS"]

Linux_distro.clear()

print (Linux_distro)

Output:

[]

Clear a list having random values

Random = ["Google", 45, "Dolphin", 23, 21]

Random.clear()

print (Random)

Output:

[]

Best,

TechBeamers