1

for example, I have this Set object:

a = {0,1,2,3,4,5}

how to randomly remove fixed number of elements from this set?

Sajuuk
  • 2,197
  • 3
  • 16
  • 32

2 Answers2

7

To remove 2 random elements, sample 2 random elements, then remove them:

a.difference(random.sample(a, 2))

or just sample two elements less than the size of the set:

set(random.sample(a, len(a) - 2))

If you want a destructive operation (so that a changes), you can use difference_update on it instead:

a.difference_update(random.sample(a, 2))
Amadan
  • 179,482
  • 20
  • 216
  • 275
0

A possible approach is to choose the number of elements to remove, iterate over the later range, and choose a value to remove:

import random
a = {0,1,2,3,4,5}
n = 2
for i in range(n):
   val = random.choice(list(a))
   a.remove(val)

Or, even shorter, a comprehension:

vals = [random.choice(list(a)) for i in range(n)]
a = {i for i in a if i not in vals}
Ajax1234
  • 66,333
  • 7
  • 57
  • 95