I want to write a program that displays all the elements of a list in random order without repetition. It seems to me that it should work, but only prints those elements with repetition.
import random
tab = []
for i in range(1, 8):
item = random.choice(["house", "word", "computer", "table", "cat", "enter", "space"])
if item not in tab:
print(item)
else:
tab.append(item)
continue
Instead of
random.choicewithin theforloop, userandom.shufflehere.This way, your list is guaranteed to be have all the elements, while also maintaining the requirement of random order:
As for your original code, that will not work, since the
if elseblock as you've written ensures that no element is added within the listtab. You could correct that by removing the else block like below:But now you will need to alter the logic so that the runs in which same value is randomly returned don't affect the number of outputs.