random from a list python code example

Example 1: how to randomly choose from a list python

random.choice(name of list)

Example 2: python random choice from list

import random
list = [20, 30, 40, 50 ,60, 70, 80]
sampling = random.choices(list, k=4)      # Choices with repetition
sampling = random.sample(list, k=4)       # Choices without repetition

Example 3: python random generator from list

import random
n = random.random()
print(n)

Example 4: select a random element from a list python

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)

Example 5: python random list

import random
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)