sample from list python code example

Example 1: python choose random sample from list

import random
sequence = [i for i in range(20)]
subset = random.sample(sequence, 5) #5 is the lenth of the sample
print(subset) # prints 5 random numbers from sequence (without replacement)

Example 2: python choose sample from list with replacement

import random

random.choices(list, k = 4)

Example 3: python equivalent of R sample function

lstDemand = [0, 1000, 2000, 3000, 4000, 5000, 6000]
lstProbability = [.02, .03, .05, .08, .33, .29, .20]

# Python Equivalent of R sample() function
numpy.random.choice(lstDemand, size=1000, replace=True, p=lstProbability)

# lstDemand = the values or options
# size = how many values the output list should have (None = 1)
# replace = sampling with or without replacement
# p = the probability of choosing each corresponding value in lstDemand

Example 4: python choose random sample from list

import random
sequence = [i for i in range(20)]
subset = sample(sequence, 5) #5 is the lenth of the sample
print(subset) # prints 5 random numbers from sequence (without replacement)