Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

>>> a=[1,2,3]

>>> a.remove(2)

>>> a [1, 3]

>>> a=[1,2,3]

>>> del a[1]

>>> a [1, 3]

>>> a= [1,2,3]

>>> a.pop(1)

2

>>> a [1, 3]

>>>

Is there any difference between the above three methods to remove an element from a list?

1 Answer

0 votes
by (106k points)
edited by

Yes, there is a difference between all three methods that you have applied in the following code:-

  • In simple terms, pop is the only one which returns the value, and remove is the only one which searches the object, while del limits itself to a simple deletion 

  • remove() method:-

This method is used for deleting the first occurrence of the number mentioned in its argument.

a=[1,2,3]

a.remove(2)

a

In You code, you have written ‘2’ in the argument and number 2’s first occurrence is at index 1, so it has been deleted and the rest list is printed as it is.

  • delete() method:-

Delete method deletes all the elements in a specified range from index “a” to index “z”.

a=[1,2,3]

del a[1]

a

image

In your code, you have mentioned index 1 so it has deleted the value at index 1 which is 2 and returned you the rest list.

  • pop() method:-

pop() method deletes the elements at the position mentioned in its arguments.

     a [1, 3]

     a= [1,2,3]

     a.pop(1)

image

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Jul 16, 2019 in Python by leealex956 (7.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...