Select a random Item from a Python List - Python Recipes

Опубликовано: 08 Ноябрь 2020
на канале: TekMinded - Python Recipes
4,058
82

This video provides a quick tutorial on how to select a random item from a Python list using the random.choice method.

SUBSCRIBE TO OUR YOUTUBE CHANNEL
   / @tekminded  


#python #recipes #dataanalytics #datascience #pandas #dataframe #random

Imagine that you want to build a magic ball functionality in a travel app where cities are picked at random from a pre-defined list of cities. In this video we review how to do that using the python random library and the choices() methods.

The process is quite simple. you just need to import the random library and then provide the list as argument to return one random items from the list. See code below:

import random
cities_to_visit=['Miami','New York','Paris','Bogota', 'Madrid']
print(random.randrange(cities_to_visit))

The implementation above assumes that every time you run the code all cities are presented as possible choices, which formally is the case of random selection with replacement.

It is also possible to implement it as a random selection without replacement. In this case we can use the python pop() method along with the random.randrange() method as noted in the code below.

import random
cities_to_visit=['Miami','New York','Paris','Bogota', 'Madrid']
while len(cities_to_visit)!=0:
print(cities_to_visit.pop(random.randrange(len(cities_to_visit))))


На этой странице сайта вы можете посмотреть видео онлайн Select a random Item from a Python List - Python Recipes длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь TekMinded - Python Recipes 08 Ноябрь 2020, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 4,058 раз и оно понравилось 82 зрителям. Приятного просмотра!