zjm1126
zjm1126

Reputation: 131

how to random a list using python

this is my code :

import random

a = [12,2,3,4,5,33,14,124,55,233,565]
b=[]
for i in a:
    b.append(random.choice(a))

print a,b

but i think maybe has a method like sort named randomList

has this method in python .

thanks

Upvotes: 2

Views: 182

Answers (4)

Remi
Remi

Reputation: 21165

>>> random.sample(a, len(a))

[14, 124, 565, 233, 55, 12, 5, 33, 4, 3, 2]

this has several advantages over random.shuffle:

All elements of a are part of the returned list. See more here.

Upvotes: 1

eumiro
eumiro

Reputation: 212835

import random

a = [12,2,3,4,5,33,14,124,55,233,565]

b = a[:]
random.shuffle(b)

# b: [55, 12, 33, 5, 565, 3, 233, 2, 124, 4, 14]

This will not modify a.

To modify a inplace, just do random.shuffle(a).

Upvotes: 5

Manuel Salvadores
Manuel Salvadores

Reputation: 16525

you could use random.shuffle

random.shuffle(a)

would give a random order of a.

Upvotes: 2

Shane Holloway
Shane Holloway

Reputation: 7842

I think you are looking for random.shuffle.

Upvotes: 3

Related Questions