What is the purpose of using [0]
in random.choices()
? Does [0]
refer to index of Lists
or of its sub-lists in the example code below? If I use [0]
, I get the single random word from the lists, which is the desired result, but if I omit [0]
, it gives the random sub-list with all of its elements.
Why it is giving the different result for the two cases?
If I try [1]
instead of [0]
, The code gives
index error: index out of range
But if I use [0]
or [-1]
, code gives the desired result.
import random
Animals = ["Cat", "Dog", "Lion", "Tiger", "Elephant"]
Fruits = ["Apple", "Orange", "Banana", "Mango", "Pineapple"]
Vegetables = ["Tomato", "Potato", "Onion", "Brinjal", "Peas"]
Lists = [Animals, Fruits, Vegetables]
word = random.choice(random.choices(Lists)[0])
print(word)
Aucun commentaire:
Enregistrer un commentaire