DEV Community

Paurakh Sharma Humagain
Paurakh Sharma Humagain

Posted on

5 2

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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay