Hgui
0
Q:

python choose random element from list

import random

#1.A single element
random.choice(list)

#2.Multiple elements with replacement
random.choices(list, k = 4)

#3.Multiple elements without replacement
random.sample(list, 4)
8
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)
3
import random

# with replacement = same item CAN be chosen more than once.
# without replacement = same item CANNOT be chosen more then once.

# Randomly select 2 elements from list without replacement and return a list
random.sample(list_name, 2)

# Randomly select 3 elements from list with replacement and return a list
random.choices(set_name, k=3)

# Returns 1 random element from list
random.choice(list_name)
1
# importing random module 
import random 
  
# declaring list 
list = [2, 2, 4, 6, 6, 8] 
  
# initializing the value of n 
n = 4
  
# printing n elements from list 
print(random.sample(list, n)) 
0
import random

# there are 2 ways for this
listofnum = [1, 2, 3, 4, 5]
# 1
print(random.choice(listofnum))

# 2
random.shuffle(listofnum)
print(listofnum)
0
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)
-1

New to Communities?

Join the community