0

I am trying to shuffle a list of tuples in Python,

import random
a = [(1,2,3),(4,5,6),(7,8,9)]
b = random.shuffle(a)

but when I run the above, b is None.

How can I shuffle a list of tuples?

martineau
  • 119,623
  • 25
  • 170
  • 301
NeutronStar
  • 2,057
  • 7
  • 31
  • 49

1 Answers1

6

To shuffle a but return the shuffled list and leave a intact use random.sample

import random
a = [(1,2,3),(4,5,6),(7,8,9)]
b = random.sample(a, k=len(a))
print(b)
#[(4, 5, 6), (7, 8, 9), (1, 2, 3)]
print(a)
#[(1,2,3),(4,5,6),(7,8,9)]

random.shuffle shuffles a list in place so the return value is None.

import random
a = [(1,2,3),(4,5,6),(7,8,9)]
random.shuffle(a)
print(a)
#[(4, 5, 6), (7, 8, 9), (1, 2, 3)]
Jab
  • 26,853
  • 21
  • 75
  • 114
  • Just an extra comment, if you need the original list just make a copy of it beforehand. – norok2 Jul 20 '19 at 21:45
  • 1
    If you read the docs it says just to use sample. – Jab Jul 20 '19 at 21:47
  • right, or use `sample()` – norok2 Jul 20 '19 at 21:48
  • I'm not sure why my answer was downvoted though. I had intentions on including more detail just needed links and such. Wanted to get the answer for why what was happening down first – Jab Jul 20 '19 at 21:50
  • I guess because of the duplicate already having an exhaustive answer, but cannot tell for sure. Perhaps this was discussed on meta? – norok2 Jul 20 '19 at 21:51
  • Ahh, page didn't update reflecting it was closed for me had to F5 – Jab Jul 20 '19 at 21:52
  • Upvoted, but I would add, the fact that mutator methods in Python tend to return `None` is merely a *convention*. Other languages or third party APIs may support fluent interfaces, in which case, mutator methods *could* return the object itself – juanpa.arrivillaga Jul 21 '19 at 00:42