If you have several arrays, how can you randomly choose one of the several arrays?

I'm currently doing a project relating to a music playlist and I need to be able to print the first letter of a specific artist and song for the user to guess however the artist and song must be random. I have made a separate array for each artist and song but I don't know how to randomly select one of these arrays for me to use.

This is my code of arrays:

BTS = ["Idol", "BTS"]
SWIFTY = ["Love Story", "Taylor Swift"]
RUTH = ["Lost Boy", "RuthB"]
ED = ["Perfect", "Ed Sheeran"]
ARIANA = ["No Tears Left To Cry", "Ariana Grande"]
DRAKE = ["In My Feeling", "Drake"]
RICKY = ["La Vida Loca", "Ricky Martin"]
IU = ["BBIBBI", "IU"]
BTS2 = ["Magic Shop", "BTS"]
PSY = ["Gangnam Style", "PSY"]

How can I randomly choose one of these arrays?

1 answer

  • answered 2018-10-22 11:45 Corentin Limier

    random.choice() does the trick.

    import random
    random.choice((BTS,SWIFTY,RUTH,ED,ARIANA,DRAKE,RICKY,IU,BTS2,PSY))
    

    You should use a dictionary, it will make your code easier to maintain if the number of tracks grows :

    musics = {
    'BTS' : ["Idol", "BTS"],
    'SWIFTY' : ["Love Story", "Taylor Swift"],
    'RUTH' : ["Lost Boy", "RuthB"],
    'ED' : ["Perfect", "Ed Sheeran"],
    'ARIANA' : ["No Tears Left To Cry", "Ariana Grande"],
    'DRAKE' : ["In My Feeling", "Drake"],
    'RICKY' : ["La Vida Loca", "Ricky Martin"],
    'IU' : ["BBIBBI", "IU"],
    'BTS2' : ["Magic Shop", "BTS"],
    'PSY' : ["Gangnam Style", "PSY"]}
    
    import random
    random.choice(list(musics.values()))