4 ways to clear a list in Python


In today’s post, we’ll discuss 4 different ways to clear a list (i.e. delete all the items in the list) in Python.

We’ll also work on a practice question that requires us to write a function that clears a list only if it contains non-integers and leaves the list intact if it doesn’t.

Here are some topics we’ll cover in the post:

  • How to clear a list in Python
  • What is slicing in Python
  • How to use the *= operator for lists
  • What happens when we assign a list to a variable
  • How to check if a list contains non-integers

Key Concepts

There are 4 main ways to clear a list in Python:

  • Using the built-in clear() method
  • Using the del keyword
  • Using the *= operator
  • Assigning an empty list to the list

Using the built-in clear() method

Let’s start with the easiest way to clear a list – using the built-in clear() method. This method deletes all the items in a list.

Let’s look at an example:

myList = [1, 2, 3, 4, 5]

print(myList)
myList.clear()
print(myList)

In the example above, we first declare and initialise a list called myList.

Next, we use the print() function to print myList, before calling the clear() function to clear it.

Finally, we use the print() function to print myList again.

If you run the code above, you’ll get the following output:

[1, 2, 3, 4, 5]
[]

As you can see from the output above, the clear() function has deleted all the elements in myList. Hence, we get an empty list when we print it the second time.

Using the del keyword

Besides using the clear() function, we can use the del keyword to clear a list. This technique gives us more flexibility. Instead of deleting all the elements in the list, we can choose to delete selective elements from the list.

To delete one element, we use the index of the element (recall that indexes start from 0). For instance, del myList[2] deletes the third element from the list.

To delete a range of elements, we use the slice notation.

What is the slice notation?

The slice notation is a convenient way to select elements from a list; its syntax is as follows:

name_of_list[start:end:step]

start refers to the index of the first element that we want to select. If this is omitted, the slice notation starts from index 0.

end refers to the index of the first element we do not want selected. If this is omitted, the slice notation selects elements from start to the end of the list.

step is optional and allows us to select elements in steps. For instance, if step equals 2, we want every second element in the list.

Let’s look at some examples:

chList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

print(chList[1:7])
print(chList[1:7:3])
print(chList[1:])
print(chList[:7])
print(chList[:])

In the example above, we first initialize a list called chList with 8 elements. 'a' is at index 0, 'b' is at index 1 etc.

Next, we use the slice notation to select various elements from chList.

[1:7] selects the elements from index 1 to 6 (since 7 is the first element we do not want to select)

[1:7:3] selects every third element from index 1 to 6.

[1:] selects elements from index 1 to the end of the list (because end is omitted).

[:7] selects elements from index 0 (because start is omitted) to index 6.

[:] selects elements from index 0 to the end of the list (because both start and end are omitted).

If you run the code above, you’ll get the following output:

['b', 'c', 'd', 'e', 'f', 'g']
['b', 'e']
['b', 'c', 'd', 'e', 'f', 'g', 'h']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

If you study the output above, you’ll notice that when the notation is [:], all the elements in chList are selected.

Hence, if we want to delete all elements from a list, we can use the [:] notation together with the del keyword. An example is shown below:

myList2 = [2, 4, 7, 8, 9]

print(myList2)
del myList2[:]
print(myList2)

If you run the code above, you’ll get the following output:

[2, 4, 7, 8, 9]
[]

Using the *= operator

Next, let’s talk about the *= operator. This operator updates a list with its contents repeated n times, where n is specified after the operator.

Let’s look at an example:

fruits = ['apple', 'banana']
fruits *= 3
print(fruits)

In the example above, fruits *= 3 updates the fruits list with its contents repeated 3 times. Hence, when we print the new value of fruits, we get the following output:

['apple', 'banana', 'apple', 'banana', 'apple', 'banana']

If we want to delete all the elements in a list, we can use *= 0. This updates the list with its elements “repeated zero times”. In other words, the list becomes an empty list.

Let’s look at an example:

myList3 = ['p', 'q', 'r', 's']

print(myList3)
myList3 *= 0
print(myList3)

If you run the code above, you’ll get the following output:

['p', 'q', 'r', 's']
[]

Assigning an empty list

Last but not least, let’s look at how we can clear a list in Python by assigning an empty list to it. An example is shown below:

myList4 = [12, 34, 1, 4, 6, 7]
print(myList4)
myList4 = []
print(myList4)

Here, we first declare and initialize a variable called myList4.

Next, we use the print() function to print the list, before assigning an empty list to it. Finally, we use the print() function to print the list again.

If you run the code above, you’ll get the following output:

[12, 34, 1, 4, 6, 7]
[]

As you can see, when we print myList4 after assigning an empty list to it, we get an empty list ([]) as the output.

Differences between the 4 ways

Before we move on to today’s practice question, let’s discuss an important difference between the four different ways of clearing a list in Python mentioned above. The last way (i.e. assigning an empty list) behaves very differently from the first three ways.

Let’s illustrate this with an example:

firstList = [1, 2, 3]
secondList = firstList

firstList.clear()

print(firstList)
print(secondList)

Here, we first declare and initialize a list called firstList. Next, on line 2, we assign firstList to a variable called secondList.

On line 4, we use the clear() function to clear the elements in firstList.

Finally, on lines 6 and 7, we use two print() statements to print the values of firstList and secondList.

If you run the code above, you’ll get

[]
[]

as the output. As you can see, both firstList and secondList become empty lists after we use firstList to call the clear() function. Surprised?

This has to do with what happens when we assign a list to a variable.

When we assign a list to a variable, the variable actually does not store the elements of the list. In other words, in our example above, the variables firstList and secondList do not store the elements 1, 2 and 3.

Rather, the variables store a reference to the elements. This reference is kind of like an address that tells Python where the elements of the list are stored (i.e. where 1, 2, and 3 are stored).

When we call the clear() function to clear a list, Python goes to this address to delete the elements there. Hence, when we print orginalList and secondList (which both store the same address), we get an empty list for both variables. Got it?

The same applies when we use the del or *=0 method to clear a list.

If you change line 4 above to

del firstList[:]

or

firstList *= 0

you’ll get the same output.

However, if you change line 4 to

firstList = []

and run the code again, you’ll get a different output this time. Specifically, you’ll get the following output:

[]
[1, 2, 3]

Notice that the value of secondList is not ‘updated’ in this case?

This is because when we assign an empty list to firstList, Python does not delete the elements in firstList. Rather, it creates a new empty list and assigns it to firstList.

firstList now stores the address of an empty list.

secondList, on the other hand, still stores the address of the list [1, 2, 3]. Hence, when we print its value, we get [1, 2, 3] as the output.

Bear this in mind when you work on the practice question later. Let’s proceed to the question now.

Practice Question

Today’s practice question requires us to write a function called clearNonIntList() that has one parameter – data.

This function clears all the elements in data if the list contains non-integers.

For instance, if data = [1, 2, 'a', 4], the function clears the list. On the other hand, if data = [1, 2, 5, 7], the function does not clear the list.

Expected Results

You can use the following statements to test your function:

a = [1, 2, 3, 'a', 6]
b = [1, 2, 4]
c = [5.4, 2, 6, 3]

clearNonIntList(a)
clearNonIntList(b)
clearNonIntList(c)

print(a)
print(b)
print(c)

You should get the following output:

[]
[1, 2, 4]
[]

Additional Notes

How to check if a value is an integer

To check if a value is an integer, you can use the isinstance() function. This function accepts two arguments – the value to check and the data type to check for.

If the value is of the specified data type, the function returns True. Else, it returns False.

For instance, if we want to check if 4.1 is an integer, we write isintance(4.1, int). We’ll get False as the result since 4.1 is not an integer.

Suggested Solution

Here’s the suggested solution for today’s practice question:

Click to see the suggested solution
def clearNonIntList(data):
    
    withNonInt = False
    
    for x in data:
        if not isinstance(x, int):
            withNonInt = True
            break

    if withNonInt:
        data.clear()

Here, we first define a function called clearNonIntList() with one parameter data.

Inside the function, we initialize a variable called withNonInt to False.

Next, we use a for loop to loop through the elements in data. If we find an element that is not an integer, the if condition on line 6 evaluates to True. When that happens, we update the value of withNonInt to True and use the break statement to exit the for loop.

Outside the for loop, we check if the value of withNonInt is True. If it is, we know that there is a non-integer in the list data. Hence, we use the clear() function to delete all the elements inside the list.

With that, the function is complete.

Written by Jamie | Last Updated September 16, 2020

Recent Posts