Beginner Python tips Day - 04 random

paurakhsharma

Paurakh Sharma Humagain

Posted on June 7, 2020

Beginner Python tips Day - 04 random
# Python Day - 04 random

import random
my_list = ['Python', 'JavaScript', 'Dart', 'Golang', 'Rust']

# choice - get a random element from a list
print(random.choice(my_list))
# Prints a single element from the list e.g 'Dart'

# choices - get number of elements from a list with replacement
print(random.choices(my_list, k=2))
# Prints a list of two elements from a list e.g ['Rust', 'Golang']
# Note: choices returns the elements with replacement meaning,
# You might get the same element more than once e.g ['Rust', 'Rust']

# sample - get number of elements from a list without replacement
print(random.sample(my_list, k=2))
# Similar to choices but you will not get same element more than once

# shuffle - shuffle the elements in a list
random.shuffle(my_list)
print(my_list)
# Prints e.g ['Golang', 'Dart', 'JavaScript', 'Python', 'Rust']
# Randomize the original list
💖 💪 🙅 🚩
paurakhsharma
Paurakh Sharma Humagain

Posted on June 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related