Friday, 4 December 2015

Python: list remove: Remove an element

List provides ‘remove’ method to remove an element ‘x’ from it.  

Syntax
list.remove(x)

‘remove’ method removes the first item from the list, whose value is x.

test.py
list=[2, 4, 6, 6, 4, 2]
print(list)

list.remove(6)
print(list)

$ python3 test.py
[2, 4, 6, 6, 4, 2]
[2, 4, 6, 4, 2]

‘remove’ method throws an error, if element is not in the list.

test.py

list=[2, 4, 6, 6, 4, 2]
print(list)

list.remove(60)
print(list)


$ python3 test.py
[2, 4, 6, 6, 4, 2]
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    list.remove(60)
ValueError: list.remove(x): x not in list


Previous                                                 Next                                                 Home

No comments:

Post a Comment