Difference between del, remove and pop on lists

0 votes

>>> 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?

Aug 1, 2018 in Python by bug_seeker
• 15,310 points
20 views

1 answer to this question.

0 votes

es, remove removes the first matching value, not a specific index:

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

>>> a.remove(2) 

>>> a [0, 3, 2]

del removes the item at a specific index:

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

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

and pop removes the item at a specific index and returns it.

>>> a = [4, 3, 5] 

>>> a.pop(1) 3 

>>> a [4, 5]

Their error modes are different too:

>>> a = [4, 5, 6]

>>> a.remove(7)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: list.remove(x): x not in list

>>> del a[7]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError:

list assignment index out of range

>>> a.pop(7)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: pop index out of range

answered Aug 1, 2018 by Priyaj
• 56,160 points

Related Questions In Python

0 votes
1 answer

What is the difference between pop() and remove()?

Array elements can be removed using pop() ...READ MORE

answered Jun 20 in Python by Nisa
• 1,090 points
13 views
0 votes
1 answer

Difference between pop and delete methods

I think you mean del() and not ...READ MORE

answered Jun 25, 2018 in Python by Hamartia's Mask
• 1,580 points
22 views
0 votes
1 answer

difference between lists and sets

There are a lot more differences such ...READ MORE

answered Jan 7 in Python by SDeb
• 12,280 points
13 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 124 views
+4 votes
6 answers
0 votes
1 answer

What is the difference between Python and IPython?

There are few differences between Python and ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 56,160 points
196 views
0 votes
1 answer

What is the difference between re.search and re.match?

The theoritical approach can be this way, re.match is ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 56,160 points
290 views