Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a random element from an array in Python? [duplicate]

The first examples that I googled didn't work. This should be trivial, right?

like image 439
Hanno Fietz Avatar asked Jun 29 '09 14:06

Hanno Fietz


People also ask

How do you pick a random element from a list without repetition in Python?

Python's random module provides a sample() function for random sampling, randomly picking more than one element from the list without repeating elements. It returns a list of unique items chosen randomly from the list, sequence, or set. We call it random sampling without replacement.

How do you select a random value in Python?

Use randrnage() to generate random integer within a range Use a random. randrange() function to get a random integer number from the given exclusive range by specifying the increment. For example, random. randrange(0, 10, 2) will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).


2 Answers

import random random.choice (mylist) 
like image 175
eduffy Avatar answered Oct 20 '22 02:10

eduffy


import random random.choice([1, 2, 3]) 
like image 23
Johan Kotlinski Avatar answered Oct 20 '22 03:10

Johan Kotlinski