DEV Community

Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

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

Top comments (0)