0 votes
1 view
in Python by (47.8k 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 (107k 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
0 votes
1 answer
asked Jul 16, 2019 in Python by leealex956 (6.5k points)
0 votes
1 answer
asked May 30, 2019 in Python by Nigam (4.1k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...