Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the Output of these Two Lists Different?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading