How to delete element from list in python || using 2 function pop() and remove()

How to delete element from list in python

In the python list we can delete an element by using three methods.

How to delete element from list in python

Delete element from list in python

1. pop()

We can use pop() function to remove item from list by index.

color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]

color.pop(2)

print(color)

Output

[ ‘Red’, ‘Green’, ‘Black’ ]

If we do not pass the index in the pop() function then it will remove the last elements from the list.

color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]

color.pop()

print(color)

Output

[ ‘Red’, ‘Green’, ‘Yellow’ ]

2. remove()

We can delete an element by using remove() function.

color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]

color.remove( ‘Green’ )

print(color)

Output

color = [ ‘Red’, ‘Yellow’, ‘Black’ ]

3. del()

We can also use the del() function to remove elements from the python list. 

color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’ ]

color.del(3)

Output

color = [ ‘Red’, ‘Green’, ‘Yellow’ ]

To remove multiple elements from the python list we can use del() function

color = [ ‘Red’, ‘Green’, ‘Yellow’, ‘Black’, ‘Pink’ ]

del color[ 1:3]

print(color)

Output

[ ‘Red’, ‘Black’, ‘Pink’ ]

Important Links: Informatics Practices

Share in a Single Click

Leave a Reply

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