Thursday, January 7, 2021

How To Remove Specified List Item In Python


In Python, we can remove elements from list using the value stored in the list or index number

The remove() method removes the specified item.

Example

Remove "Banaras":

mylist = ["Assam","Banaras","Chennai"]

mylist.remove("Banaras")

Now the list will be ["Assam","Chennai"]


Remove Specified Index

The pop() method removes values from list of the specified index.

Example

Remove the second item:

mylist = ["Assam","Banaras","Chennai"]

mylist.pop(1)

Now the list will be ["Assam","Chennai"]


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

Example

Remove the last item:

mylist = ["Assam","Banaras","Chennai"]

mylist.pop()

The list will be ["Assam","Banaras"]


The del keyword also removes the specified index:

Example

Remove the first item:

mylist = ["Assam","Banaras","Chennai"]

del mylist[0]

Now the list will be ["Banaras","Chennai"]


The del keyword can also delete the list completely.

Example

Delete the entire list:

mylist = ["Assam","Banaras","Chennai"]

del mylist

Clear the List


The clear() method empties the list.

The list still remains, but without any elements.

Example

Clear the list content:

mylist = ["Assam","Banaras","Chennai"]

mylist.clear()


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner