-4
list = [0, 1, 2, 8, 2, 9, 2]

Is there a way to remove the element 2, exactly one time?

So you will get:

list = [0, 1, 2, 8, 9, 2]

I tried to work with index() but I didn't found it.

It can be a RANDOM 2.

So I can't use remove() or pop() because it will not remove the number 2 on a random position.

Victor
  • 65
  • 7

4 Answers4

6

This works

list.remove(2)

L.remove(value) -- remove first occurrence of value.

Raises ValueError if the value is not present.

Bridgekeeper
  • 354
  • 2
  • 12
1

Use del or pop

For example,

del list[2]

or

list.pop(2)

The difference between del and pop is that

del is overloaded.

for example, del a[1:3] means deletion of elements 1 and 3

신형준
  • 11
  • 1
1

To randomly remove occurrence of 2

Notes:

  • we create a list of indexes of the number 2 i.e. [i for i, j in enumerate(lst) if j == 2]
  • Using random module choice method to get one index randomly from the index list
  • list pop method or remove method it's up to your choice

Code:

import random
lst = [0, 1, 2, 8, 2, 9, 2]
lst.pop(random.choice([i for i, j in enumerate(lst) if j == 2]))
print lst

output:

[0, 1, 8, 2, 9, 2]
Community
  • 1
  • 1
The6thSense
  • 8,103
  • 8
  • 31
  • 65
0

Note that you're shadowing the built-in list. Apart from that index works just fine:

>>> li = [0, 1, 2, 8, 2, 9, 2]
>>> li.pop(li.index(2))
2
>>> li
[0, 1, 8, 2, 9, 2]
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69