How can I empty the contents of a list?

Question

If I have a list containing items, how can I empty or delete all the contents of the list?

Answer

There are two ways to empty an existing list. The first way is to just assign the list variable to an empty list. In this case, the old list and its contents are automatically deleted by Python. This is shown in the following code example.

list1 = [ 1, 2, 3, 4, 5, 6, 7 ]
list1 = []

The second method is to use the del() function to delete all the elements of the list. This forces the removal of all the items immediately instead of letting Python delete the contents at some time of its choosing. Both methods produce the same end result which is that the list will be empty of contents.

list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
del list2[:]
20 Likes

In the second example above it is important to include the slice subscript, else the variable itself will be deleted.

>>> list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
>>> del list2[:]
>>> list2
[]
>>> isinstance(list2, list)
True
>>> list2 = [ 10, 20, 30, 40, 50, 60, 70 ]
>>> del list2
>>> isinstance(list2, list)
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    isinstance(list2, list)
NameError: name 'list2' is not defined
>>> 

Clearly, the first example is the preferred approach, assign an empty list, since it is not likely to ever throw a wrench into the proceedings (a bug that could be tricky to find).

57 Likes

what if we want to delete a single or some specific elements from the list? how can we do that?

4 Likes

We have two choices,

  • delete by value
  • delete by index

Which is it you wish to do?

3 Likes

Could you please explain both? I want to learn.

1 Like

Have you explored the docs.python.org material, yet, just from a familiarization perspective. It is a good first step. Take the time to look things over then come back and start learning how to put the pieces together. It’s not a novel; just focus on the parts your are most concerned with at the time.

How to delete item or items from a list python

4 Likes

Does this mean, that when we use :

list1 = [1,2,3,4]
list1 =

delete’s the list1 i.e. python does not anymore remember us creating one?

The first entry has list1 referencing a list. That reference remains intact until the variable is given a new reference, the empty list. It no longer references the populated list, which if no other references exist will be garbage collected and the memory re-allocated.

It appears as though the second assignment has just emptied the list, but that is not so. If we check the ID of each reference we will see they are not the same object.

Consider,

>>> list1 = [1, 2, 3, 4]
>>> id(list1)
48786408
>>> del list1[:]
>>> list1
[]
>>> id(list1)
48786408
>>> list1[:] = [1, 2, 3, 4]
>>> list1
[1, 2, 3, 4]
>>> id(list1)
48786408
>>> 

Notice that as long we operate on the contents of the list, the ID remains the same, even when the list is emptied (but not replaced).

Now lets see what happens when we replace the list.

>>> list1 = []
>>> id(list1)
48829504
>>> 

It now references a completely new object. As mentioned, if no other references exist within the program to the original object, the earlier ID will no longer exist.

8 Likes

Hello, I have a question if you will. Say you try this code to empty a list:

chips_eaten = [1,2,3,4,5]
chips_eaten[:5] = []
print(chips_eaten) # prints [] to console

Would this possibly open the door for future bugs?

1 Like

For starters, we would want to have a reason to clear the list, and there is an easier way to do that.

chips_eaten = []

or

chips_eaten.clear()  # in situ (needs no assignment)
2 Likes

Thanks~ So need to complicate things when there is a shorter faster method. :slight_smile:

It still comes down to why we would need to clear a list. The rest is moot. It has nothing to do with what is shorter or faster, but what works in a dynamic environment and is also readable.

1 Like

Okay so then three factors impact a given code’s best fit: circumstance, ease of application, and how well the code communicates its function.

Is that right?

Those are all reasonable factors, on top of reliability; the code must work as expected.

1 Like

Thanks for this comment. I can see how that would genuinely be a problem to bug in the future.

1 Like

Dear mtf,

Great explanation as always! There is a world of difference between emptying a list and clearing out the variable from memory entirely.

I don’t think I’ve seen the slice/subscript syntax covered in this course yet, but I’m looking forward to it if it’s covered later on in the course.

Best regards,
Tobis

1 Like

In a real world application, how is this useful, could you maybe give some examples or ideas to recreate this in a portfolio application?

Different scenarios crop up all the time where we may need to clear a list while keeping it declared. Not being a real world programmer it is difficult to dream up such scenarios. This is merely an example of the various ways we can clear a list.