Categories We Write About

Build a random playlist generator

Here’s a complete Python script for a random playlist generator that you can run locally or adapt for a web app. It takes a list of songs and outputs a randomly shuffled playlist each time you run it.

python
import random def generate_random_playlist(songs, playlist_length=None): """ Generate a random playlist from the given list of songs. :param songs: List of song titles (strings) :param playlist_length: Optional integer specifying desired length of playlist If None, generates playlist with all songs shuffled. :return: List of songs in random order """ if not songs: return [] # If playlist length not specified or longer than available songs, use all songs if playlist_length is None or playlist_length > len(songs): playlist_length = len(songs) # Randomly sample songs without replacement playlist = random.sample(songs, playlist_length) return playlist # Example usage if __name__ == "__main__": songs_library = [ "Song A - Artist 1", "Song B - Artist 2", "Song C - Artist 3", "Song D - Artist 4", "Song E - Artist 5", "Song F - Artist 6", "Song G - Artist 7", "Song H - Artist 8", "Song I - Artist 9", "Song J - Artist 10" ] playlist = generate_random_playlist(songs_library, playlist_length=5) print("Random Playlist:") for idx, song in enumerate(playlist, 1): print(f"{idx}. {song}")

How it works:

  • Takes a list of songs.

  • Optional parameter lets you choose how many songs you want.

  • Uses random.sample to avoid duplicates in the playlist.

  • Prints the randomized playlist.

Would you want me to create a web version in JavaScript or something more advanced?

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About