Reputation: 3
I want to randomly assign the three items from list into randlist but I also don't want the items to be assigned more than once
I tried to use a while loop that would pop the items randomly into randlist but it seems to be taking characters from the array item instead of the entire string.
from random import randint
list = ["car", "zonk1", "zonk2"]
randlist = []
x = 0
while x < 3:
randlist += list.pop(randint(0, len(list) - 1))
x += 1
door1 = randlist[0]
door2 = randlist[1]
door3 = randlist[2]
print (door1, door2, door3)
Result:
z o n
Upvotes: 0
Views: 109
Reputation: 535
If you are willing to use numpy. Then the following code is slightly faster (and arguably neater) than for-looping:
import numpy as np
_list = ["car", "zonk1", "zonk2"]
idx = np.random.permutation(len(_list))
mylist = list(np.array(_list)[idx])
Example output:
>>> mylist
['zonk1', 'car', 'zonk2']
Upvotes: 0
Reputation: 95993
This line:
randlist += list.pop(randint(0, len(list) - 1))
extends the str
object, character by character, into the list.
>>> mylist = []
>>> mylist += 'foo'
>>> mylist
['f', 'o', 'o']
You want to append what you are popping.
>>> mylist = []
>>> mylist.append('foo')
>>> mylist
['foo']
As an aside, you should use other functions in the random
module instead of re-inventing the wheel. You want a random sample from your list:
>>> import random
>>> mylist = ["car", "zonk1", "zonk2"]
>>> random.sample(mylist, 3)
['zonk1', 'car', 'zonk2']
>>> random.sample(mylist, 3)
['zonk2', 'car', 'zonk1']
>>> random.sample(mylist, 3)
['car', 'zonk2', 'zonk1']
Upvotes: 3