1

I have a playlist which has the name of it in the first index, and then sublists for each song with its artist and genre. I want to shuffle the songs but without the playlist name changing.

Doing just random.shuffle on the list does not work because the playlist name gets shuffled around too and I would like to stay at index 0.

playlist = ['pop music', ['song A', 'artist A', 'Pop'], ['song B', 'artist B', 'Pop']]
random.shuffle(playlist)
ggorlen
  • 44,755
  • 7
  • 76
  • 106
b0fa
  • 23
  • 3
  • I think a neat one-liner would use lambda-expressions: `shuffled = sorted(playlist[1:], key=lambda l: random.random()).insert(0, playlist[0])` – Lone Lunatic Nov 09 '19 at 00:08

3 Answers3

4

You can use a slice to extract the tail of the list, then pass this chunk into shuffle, then concatenate the parts back together:

import random

playlist = list(range(10))
tail = playlist[1:]
random.shuffle(tail)
playlist = playlist[:1] + tail
print(playlist)

shuffle is in-place, so it's a bit awkward to use.


Also, if your data structure is requiring a bit of this extra fussing to use cleanly, you might consider refactoring it to a dictionary that uses playlist names as keys and the constituent tracks associated with that playlist as a list of values, each of which is a dict of track data. For example:

playlists = {
    "pop": [{"artist": "Rhianna", "track": "Diamonds"}, ...],
    "black metal": [{"artist": "Burzum", "track": "Stemmen fra tårnet"}, ...],
    "children": [{"artist": "Raffi", "track": "Bananaphone"}, ...]
    ...
}

Then it's a matter of shuffle(playlists["pop"]). Obviously, this structure could get complicated pretty quickly depending on how much data you're managing, but all the more reason to set it up cleanly.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Nice one @ggorlen. I like these answers for beginners without resorting to numpy, lambdas, etc. – Raphael Nov 09 '19 at 00:13
0
import random
playlist = ['pop music', ['song A', 'artist A', 'Pop'], ['song B', 'artist B', 
'Pop']]
ii = 0
iii = []
x = 0
playlist1 = []
for i in playlist:
  playlist1.append(playlist[0])
  x += 1
for i in playlist1:
  g1 = random.choice(playlist)
  iii.append(g1)
  playlist.remove(g1)
  ii += 1
playlist = iii
PythonNerd
  • 293
  • 1
  • 11
0

The following code is a simple way to do it in-place. The code extracts the songs, shuffles them, then replaces them in the original list.

songs = playlist[1:]  # Extracts everything in the playlist except the genre.
random.shuffle(songs)
playlist[1:] = songs  # Updates song portion of list with shuffled version.
martineau
  • 119,623
  • 25
  • 170
  • 301