-1

I have this problem, I have a sample list:

list = [6, 4, 5, 3, 10]

However, I need to remove the elements by index, and when I try to remove "4", I popped the item in index 4.

list.pop(4)
print(list)
Output:
list = [6, 4, 5, 3]

Is there a way I can get past this?

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Daniel Poh
  • 129
  • 1
  • 10
  • Possible duplicate of [How to remove an element from a list by index in Python?](https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index-in-python) – M.T Mar 31 '18 at 13:06

4 Answers4

1

`

list = [6, 4, 5, 3, 10]
del list[4]
print(list)
Output:
list = [6, 4, 5, 3]

`

AFault
  • 9
  • 2
1

If you know the index of the value stored inside a list. Python provides a nice way to remove that using pop method.

list.pop(indexWhichYouWantToDelete)

Difference between del, remove and pop on lists

check this qna for more clarification.

Thank you

Amit Singh
  • 33
  • 3
0

You can get the index of the element you want to pop with list.index(4) and use it.

list.pop(list.index(4))
MingiuX
  • 100
  • 4
0

There can be more than one existence of an element. So, the solution is:

lis = [2,3,4,1,3,5,3]
while 3 in lis:
  i = lis.index(3)
  lis.pop(i)
print(lis)
arctic_Oak
  • 974
  • 2
  • 13
  • 29