import random
words = ['nugget', 'jasmine', 'trolley', 'weight', 'soap']
mywords = []
random.shuffle(words)
mywords.append(random.sample(words, 2))
print("Words: ")
for i in words:
print(str(i))
print("My Words: ")
for i in mywords:
print(str(i))
I am working on an example that moves items from one list to another. The example seems to work as intended except for the output of the second list 'mywords', which prints in brackets and not as an unordered list as the list 'words' prints. Any suggestions? My guess is it has something to do with the append function I used.
CodePudding user response:
The function random.sample()
returns a list. The function list.append()
takes the item you pass as an arugment, in this case a list
, and adds it to the end of your list. If you replace append()
with extend()
it will add each item returned from random.sample()
to the list individually.
CodePudding user response:
random.sample(words,2)
creates a list of 2 words that are then appended as the only element of mywords. I suggest you might want to use mywords = random.sample(words, 2)
instead.