2

How to find and delete only one element in a list in Python?

# Example:deleting only the first (1,2) in the list
a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
# result expected
a = [(4, 5), (7, 5), (1, 2), (5, 2)]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user3346439
  • 113
  • 1
  • 1
  • 9

2 Answers2

3

Use the list.remove() method to remove the first occurrence, in-place:

a.remove((1, 2))

Demo:

>>> a = [(4, 5), (1, 2), (7, 5), (1, 2), (5, 2)]
>>> a.remove((1, 2))
>>> a
[(4, 5), (7, 5), (1, 2), (5, 2)]

See the Mutable Sequence Types documentation:

s.remove(x)
same as del s[s.index(x)]

and s.index() only ever finds the first occurrence.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

Hello if you want to delete any thing in lists

use these codes

mylist.pop(element_order) #mylist stands for your list and
#element_order stands for the order of element is the list and if it is the 
#first element it will be 0

or you can use

mylist.remove(the_element)

note that in the pop it is a method not a list

mylist.pop(0)
print mylist

dont use

mylist = mylist.pop(0)