Hi everyone, welcome back. In these examples, we will be going over how to remove elements from a List in Python. Lists can be used to store a collection of data. A List in Python is mutable and can allow duplicate values. The elements within a List are indexed and ordered. With this introduction out of the way, let's get into it.

Creating List

Let's start by creating our List with populated values:

myList = [1, 2, 3]
print(myList)
Output:
[1, 2, 3]

So now, we have a populated List with a few elements. We can verify that it was successfully created and populated by printing the List and checking the output. Now, let's see how we can remove elements.

Removing by Value

Let's try to remove an element from the List by its value. We can do this by using the built in remove() function that is provided. Let's see an example:

myList = [1, 2, 3]
myList.remove(1)
print(myList)
Output:
[2, 3]

In the example above, we can see that we removed the number "1" from our List by using the remove() function. We can verify that it was successfully removed by printing our List and checking the output.

Removing by Index Number

Now, let's try to remove an element from the List by its index number. We can do this by using the built in pop() function that is provided. Let's see an example:

myList = [1, 2, 3]
myList.pop(0)
print(myList)
Output:
[2, 3]

In the example above, we can see that we removed the element with the index number of "0" from our List by using the pop() function. We can verify that it was successfully removed by printing our List and checking the output.

Now, let's see what happens if we use the pop() function without providing an index number:

myList = [1, 2, 3]
myList.pop()
print(myList)
Output:
[1, 2]

If we don't provide an index number for the pop() function, it will remove the last element in the List, as shown in the example above.

Clearing out a List

Now, let's try to clear out a List entirely. We can do this by using the built in clear() function that is provided. Let's see an example:

myList = [1, 2, 3]
myList.clear()
print(myList)
Output:
[]

In the example above, we can see that we cleared out the entire List by using the clear() function. We can verify that it was successfully removed by printing our List and checking the output.

Conclusion

That is it for the removing elements from a Python List examples. We covered how to remove elements by value and index number by using the remove() and pop() functions. Along with how to clear out a List entirely with the clear() function. I hope this helps. If there are any questions or comments, please let me know. Thanks for reading.