Home > other >  How To Print Multiple Different Data From Same Array?
How To Print Multiple Different Data From Same Array?

Time:06-07

I want to print multiple different data from the same array, but I don't know how. Can someone show me? Like I want to print a random letter every time from the same array. Is there a command?

CodePudding user response:

Well, you can print something random from an Array by generating a random Number and printing that Value from a List:

import random

my_list = [1,2,3,4,5] # your list

x = random.randint(0,len(my_list)) # generate a random number from 0-the length of your list

print(my_list[x]) # print the value

I believe there is definetly a better solution to this but that is how I would have done it.

CodePudding user response:

Python's standard library comes with a random module which has methods like

random.choice(your_list) which gives you 1 random choice from your array

random.choices(your_list, n) which will give you n number of choices from your list but there may be duplicates

random.sample(your_list, n) which will give you n random unique choices from your list

random.shuffle(your_list) which will shuffle all the items in your list randomly inplace

Example code

import random

my_list = [1, 2, 5, 3, 9]

print(random.choice(my_list)) # gives 1 random choice
print(random.choices(my_list, 4)) # gives 4 random choices
print(random.sample(my_list, 4) # gives 4 unique choices
random.shuffle(my_list) # shuffles list inplace
print(my_list)
  • Related