8
thelist = ['a','b','c','d']

How I can to scramble them in Python?

user2284570
  • 2,891
  • 3
  • 26
  • 74
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

5 Answers5

19
>>> import random
>>> thelist = ['a', 'b', 'c', 'd']
>>> random.shuffle(thelist)
>>> thelist
['d', 'a', 'c', 'b']

Your result will (hopefully!) vary.

Peter
  • 127,331
  • 53
  • 180
  • 211
17
import random
random.shuffle(thelist)

Note, this shuffles the list in-place.

Phil
  • 4,767
  • 1
  • 25
  • 21
8

Use the random.shuffle() function:

random.shuffle(thelist)
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
6

Use the shuffle function from the random module:

>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
1

in-place shuffle (modifies v, returns None)

random.shuffle(v)

not in-place shuffle (if you don't want to modify the original array, creates a shuffled copy)

v = random.sample(v, len(v))
Omar Cusma Fait
  • 313
  • 1
  • 11