Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does anyone know a way to scramble the elements in a list?

Tags:

python

random

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

How I can to scramble them in Python?

like image 848
TIMEX Avatar asked Oct 06 '09 07:10

TIMEX


People also ask

How do you shuffle elements in a list?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

How do you randomly permute a list in Python?

The random. sample() function returns the random list with the sample size you passed to it. For example, sample(myList, 3) will return a list of 3 random items from a list. If we pass the sample size the same as the original list's size, it will return us the new shuffled list.

How do you shuffle items in an array Python?

Shuffle an Array in Python Using the random. The random. shuffle() method takes a sequence as input and shuffles it. The important thing to note here is that the random. shuffle() does not return a new sequence as output but instead shuffles the original sequence.


5 Answers

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

Your result will (hopefully!) vary.

like image 102
Peter Avatar answered Oct 05 '22 19:10

Peter


import random
random.shuffle(thelist)

Note, this shuffles the list in-place.

like image 24
Phil Avatar answered Oct 05 '22 19:10

Phil


Use the random.shuffle() function:

random.shuffle(thelist)
like image 24
Greg Hewgill Avatar answered Oct 05 '22 18:10

Greg Hewgill


Use the shuffle function from the random module:

>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']
like image 44
RichieHindle Avatar answered Oct 05 '22 19:10

RichieHindle


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))
like image 36
Omar Cusma Fait Avatar answered Oct 05 '22 19:10

Omar Cusma Fait