1

I have a question regarding the .pop() method. In the documentation, it states that on sets:

Remove and return an arbitrary element from the set.

So what exactly does "arbitrary" mean? Like, for example: If I wanted to build a queue from a list of users where position is determined at random, could I enter in all users into a set, and then build a randomly assigned queue using .pop()?

So the code would look something like

queue_set = {'bob','rachel','sara','david'}
queue = dequeue([])
while queue_set:
        queue.append(queue_set.pop())

Would that be a reasonable way to randomly assign members to an index? Or is the .pop() reliant on some way the data is entered or something?

Thanks!

Kevin
  • 28,963
  • 9
  • 62
  • 81
Djones4822
  • 577
  • 3
  • 6
  • 23

2 Answers2

5

No.

"Arbitrary" means the implementation returns whichever element is most convenient. You are not guaranteed randomness. Use random.sample() or random.shuffle() if you need random selection.

Kevin
  • 28,963
  • 9
  • 62
  • 81
1

I think the best way would be to use random.shuffle

>>> import random
>>> li = ["bob", "rachel", "sara", "david"]
>>> random.shuffle(li)
>>> li
['sara', 'bob', 'david', 'rachel']

If you want to get the elements one by one, you can then use li.pop().

legaultmarc
  • 127
  • 1
  • 10