简体   繁体   中英

Removing element in a list

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.

This works

list.remove(2)

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

Raises ValueError if the value is not present.

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

To randomly remove occurrence of 2

Notes:

  • we create a list of indexes of the number 2 ie [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]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM