How to choose random element from a list in python. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
10th Apr 2019, 3:52 PM
Usama Navid
Usama Navid - avatar
11 Answers
+ 7
Use the choice method of the module rand. Example: import random arr = [1,2,3,4,5,6] print(random.choice(arr)) #a random entry in the list
10th Apr 2019, 4:02 PM
Seniru
Seniru - avatar
+ 6
hi, you may also use this: import random rand_val = random.randint(1,6) This generates a random value to var “rand_val” which can use.
10th Apr 2019, 4:09 PM
Lothar
Lothar - avatar
+ 5
Muhammad Usama Navid you are required to use it in your code for random things unless you wrote your own library 😜
10th Apr 2019, 4:13 PM
Seniru
Seniru - avatar
+ 5
Muhammad Usama Navid you have passed the input for the choice method. So the only possible value to return is the input. Change it to this x=random.choice(dice)
10th Apr 2019, 4:21 PM
Seniru
Seniru - avatar
+ 5
Muhammad Usama Navid it's common to everyone 😅. You just need to be more careful and a good detective 😂😂. BTW I hope you got this answer
10th Apr 2019, 4:24 PM
Seniru
Seniru - avatar
+ 5
from random import randint list = [4, 5, 3, 7, 1, 9] x = randint(0, 5) print(list[x])
14th May 2019, 1:49 PM
Nerderkips
Nerderkips - avatar
+ 4
In my code mentioned above why this library always chose the same thing that I have given in input.
10th Apr 2019, 4:16 PM
Usama Navid
Usama Navid - avatar
+ 4
Oh sorry 🙏 how non serious am I.
10th Apr 2019, 4:22 PM
Usama Navid
Usama Navid - avatar
+ 4
Muhammad, put the statement for import at the top of your source code.
10th Apr 2019, 5:04 PM
Lothar
Lothar - avatar
+ 3
Do I need to put "import random" somewhere in the code.
10th Apr 2019, 4:10 PM
Usama Navid
Usama Navid - avatar
+ 2
Example: import random arr = [1,3,5,8,9,10] print(random.choice(arr))
12th Apr 2019, 1:15 PM
Ridjeik
Ridjeik - avatar