thelist = ['a','b','c','d']
How I can to scramble them in Python?
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.
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.
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.
>>> import random
>>> thelist = ['a', 'b', 'c', 'd']
>>> random.shuffle(thelist)
>>> thelist
['d', 'a', 'c', 'b']
Your result will (hopefully!) vary.
import random
random.shuffle(thelist)
Note, this shuffles the list in-place.
Use the random.shuffle()
function:
random.shuffle(thelist)
Use the shuffle
function from the random
module:
>>> from random import shuffle
>>> thelist = ['a','b','c','d']
>>> shuffle(thelist)
>>> thelist
['c', 'a', 'b', 'd']
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With