11.4 Remove List Items

By | October 2, 2021

Remove Specified Item

The remove() method removes the specified item.

Example

Remove “banana”:
thislist = [“apple”, “banana”, “cherry”]
thislist.remove(“banana”)
print(thislist)

Output:
[‘apple’, ‘cherry’]

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:
thislist = [“apple”, “banana”, “cherry”]
thislist.pop(1)
print(thislist)

Output:
[‘apple’, ‘cherry’]

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:
thislist = [“apple”, “banana”, “cherry”]
thislist.pop()
print(thislist)

Output:
[‘apple’, ‘banana’]

The del keyword also removes the specified index:

Example

Remove the first item:
thislist = [“apple”, “banana”, “cherry”]
del thislist[0]
print(thislist)

Output:
[‘banana’, ‘cherry’]

The del keyword can also delete the list completely.

Example

Delete the entire list:
thislist = [“apple”, “banana”, “cherry”]
del thislist
#this will cause an error because you have succsesfully deleted “thislist”.

Output:
Traceback (most recent call last):
  File “demo_list_del2.py”, line 3, in <module>
    print(thislist) #this will cause an error because you have succsesfully deleted “thislist”.
NameError: name ‘thislist’ is not defined

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

Example

Clear the list content:
thislist = [“apple”, “banana”, “cherry”]
thislist.clear()
print(thislist)

Output:
[ ]

Leave a Reply

Your email address will not be published. Required fields are marked *