Back

Selecting a random sample

You can pick a single random item from a list easily in Python using the random module and the choice method.

Q1. Get this code working:

sport=['football','hockey','rugby','rounders','horse racing','high jump','long jump']
print(sport)

for number in range(100):
    myChoice = random.choice(sport)
    print(myChoice)

Q2. Describe what this code does.
Q3. Use the extend method to add swimming and running to the list of sports. Print out the new list and test it works.

You can produce a new random list from an existing list of items easily using the random module and the sample method.

Q4. Get this code working:

import random

breakfast=['eggs','bacon','sausages','mushrooms','black pudding','fried bread','tomatos']
for number in range(100):
    myChoice = random.sample(breakfast,4)
    print(myChoice)

Q5. Describe how this code works.
Q6. Modify the program so hash browns and white pudding are added to the breakfast list using an appropriate list method. Test it.
Q7. Modify the program so that five items are selected each time the program runs. Test it.
Q8. Using an appropriate method, delete mushrooms from the list. Print out the new breakfast list.
Q9. Display the number of items in the breaksfast list.
Q10. Make up your own list of ten items and randomly pick three of them. 

Back