- [Instructor] In this video,
we're going to introduce another way
to delete elements from a list,
using the del, or delete, statement,
which is not only capable of deleting from a list,
but also capable of deleting variables
from an Interactive Python session as well.
So we'll demonstrate those cases to you.
Now, for the purpose of this example,
we'll once again work with a list of numbers.
For this one, let's say we want to produce the range
of values zero through nine.
And, of course, if we go ahead and evaluate numbers,
we can see the contents of that list.
Now, the del statement can be used to remove,
from a list, any valid index position
or any subset slice that you specify.
So, for example, if I go ahead and say
del numbers sub minus one,
that says delete the last element of the list.
And if I now go and reevaluate numbers,
we can see there's one fewer element in the list.
The nine has been removed.
Now, like I said, you can also delete slices.
So if I say delete numbers
sub zero colon two,
and again, zero in this case is implicit
because it's the start of the list,
so I could just say del numbers colon two
in the square brackets,
and in this case,
we can go ahead and take a look at numbers
and see that the first two elements,
the slice from zero,
up to but not including index position two,
has been removed from the beginning of the list.
Now, as you might expect,
you don't have to delete consecutive elements
in a slice because any valid slice can be used.
So if I now go ahead and say
let's delete from numbers every other remaining element,
that's going to start from index zero,
which will be inferred as the first index,
go all the way through the list,
so the length of the list will be inferred
as the second index,
and every other element will be removed.
So we'll delete the two, four, six, and eight
from the remaining list,
and if we now go ahead and evaluate numbers,
we see that only three, five, and seven are remaining.
And, as you would also probably expect now
based on what we've shown you with slices,
we could even do delete numbers colon,
in square brackets, which just says delete all the elements
of the list numbers,
and now it is an empty list.
So, as I mentioned towards the beginning of this video,
in addition to being able to delete elements from a list,
which is a mutable object,
so you can't do this for slices or strings for example,
but in addition to modifying lists,
you can also delete variables
from the current session as well.
So if I simply say delete numbers,
that literally says remove the variable numbers
from this interactive IPython session.
So now if I try to evaluate numbers,
it tells me that that name is not defined
here in the current session.