1

I want to shuffle a list 6 times but I keep getting the same result for all the 6 occasions. Can somebody help me find where the fault is?

Here is the code I used

import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    random.shuffle(lis1)
    lis2.append(lis1)
print lis2

And here is a sample result I got

[[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0],[1,3,2,0]]

If I get jumbled lists, how can I sort them in ascending order? As in,I want to get this -

[[0,1,2,3],[2,3,1,0],[2,1,3,0],[1,0,3,2]]

into this-

[[0,1,2,3],[1,0,3,2],[2,1,3,0],[2,3,1,0]]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
S.Dan
  • 1,826
  • 5
  • 28
  • 55
  • 1
    You are shuffling and appending the **same** list 6 times. – user2864740 Oct 17 '14 at 06:16
  • See http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – user2864740 Oct 17 '14 at 06:17
  • possible duplicate of [Python initializing a list of lists](http://stackoverflow.com/questions/12791501/python-initializing-a-list-of-lists) (see the answer, the `*` syntax is different but the result/issue is the same) – user2864740 Oct 17 '14 at 06:24

4 Answers4

4

First, your code repeatedly inserts a lis1 reference into lis2. Since lis1 stays the same all this time, all of lis2 elements end up pointing to the same object. To fix this, you need to change the append() line to make a copy of the list each time:

lis2.append(lis1[:])

Now, to sort the result simply call sort() after the loop:

lis2.sort()
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

Try something simpler:

>>> first = [0,1,2,3]
>>> jumbled = [random.sample(first, len(first)) for i in range(6)]
>>> ordered = sorted(jumbled)
>>> jumbled
[[0, 3, 2, 1], [1, 0, 2, 3], [0, 2, 1, 3], [0, 1, 2, 3], [0, 2, 3, 1], [0, 3, 2, 1]]
>>> ordered
[[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 2, 1], [0, 3, 2, 1], [1, 0, 2, 3]]
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
2

Store copy of lis1 not actual lis1 do this:

lis2.append(lis1[:])

Then code will be:

import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    random.shuffle(lis1)
    lis2.append(lis1[:])

print lis2

Output:

[[2, 3, 1, 0], [0, 3, 2, 1], [3, 0, 1, 2], [1, 2, 0, 3], [3, 0, 2, 1], [1, 0, 3, 2]]
fredtantini
  • 15,966
  • 8
  • 49
  • 55
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
0
import random
lis1=[0,1,2,3]
lis2=[]
for i in range(6):
    r = random.randint(0,len(lis1))
    #print(r)
    lis2.append(lis1[r:]+lis1[:r])
print(lis2)
print(sorted(lis2))
Ashwani
  • 1,938
  • 11
  • 15