random - Python list does not shuffle in a loop -


i'm trying create randomized list of keys iterating:

import random  keys = ['1', '2', '3', '4', '5'] random.shuffle(keys) print keys 

this works perfect. however, if put in loop , capture output:

a = [] x in range(10):     random.shuffle(keys)     a.append(keys) 

i getting 10 times of same shuffle?! fundamentally wrong here... in advance.

the problem shuffling list in place , adding reference of list combined list. end same list structure 10 times. "fundamental change" list has copied before appending it.

here bit more "pythonic" way of achieving same result list comprehension.

 import random  def shuffleacopy(x):         b = x[:] # make copy of keys         random.shuffle(b) # shuffle copy         return b # return copy  keys = [1,2,3,4,5,6,7,8] = [shuffleacopy(keys) x in range(10)] print(a) 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -