Randomize lists

Asked 2 years ago, Updated 2 years ago, 92 views

For example, what should I do if I want to show off 100 random things out of a thousand lists...?

python list random

2022-09-22 16:10

1 Answers

You can use the random module.

If you allow duplication, it is convenient to use List compression and choice functions If you do not allow duplication, you can use the sample function.

import random

# Allow duplication
count = 2
sampleList = ['a', 'b', 'c', 'd', 'e']
print [random.choice(sampleList) for i in range(count)]

# Allow Duplicate X 
print random.sample(sampleList, count)


2022-09-22 16:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.