2

So, recently I've had trouble getting random.shuffle to randomly pick and execute a function from a list. I've been able to get that process working but now I want the questions to be removed from the list once they're picked. I'll show you the code that should work in theory, but just randomly picks questions and repeats them.

while 1:
    questionList = [Question1, Question2, Question3, Question4, Question5]
    random.shuffle(questionList)
    print(questionList.pop()())

If you have any idea of how to get the result I'm looking for, don't be afraid to comment or add a new answer!

~Cheers!

Bahrom
  • 4,752
  • 32
  • 41
Chris
  • 339
  • 1
  • 2
  • 8
  • 1
    Possible duplicate of [What is the most pythonic way to pop a random element from a list?](http://stackoverflow.com/questions/10048069/what-is-the-most-pythonic-way-to-pop-a-random-element-from-a-list) – R Nar Jun 15 '16 at 20:44
  • Your code should work. Are you sure your `QuestionX` objects are working as you expect? – Tom Dalton Jun 15 '16 at 20:45
  • You're recreating the `questionList` every time round the loop! – Tom Dalton Jun 15 '16 at 20:45

2 Answers2

1

You're recreating the questionList every time round the loop!

Try this:

questionList = [Question1, Question2, Question3, Question4, Question5]
random.shuffle(questionList)
for q in questionList:
    print(q())
Tom Dalton
  • 6,122
  • 24
  • 35
1

The problem is that you always set the questionList in the while loop, replacing it each time with a freshly filled version with all questions. If you move it out of the loop it should work fine.

Also, shuffling once is enough, so you can also move that out of the loop too.

In addition, while 1 will never stop, which will raise an error once all questions are removed. If you use while questionList instead the loop will stop once all questions are used up:

questionList = [Question1, Question2, Question3, Question4, Question5]
random.shuffle(questionList)
while questionList:
    print(questionList.pop()())
Leon
  • 2,926
  • 1
  • 25
  • 34