2

This is what I have:

>>> import random
>>> chars = [1, 6, 7, 8, 5.6, 3]
>>> for k in range(1, len(chars)+1):
...   print random.choice(chars)
...   chars[random.choice(chars)] = ''
...

But when I run it,

5.6
1

5.6

8
>>> 

I don't want it to print a random amount of each one, I want it to print all of the content once, in a random order. And why is it printing spaces?

5 Answers5

3

Try this:

import random
chars = [1, 6, 7, 8, 5.6, 3]
r = chars [:] #make a copy in order to leave chars untouched
random.shuffle (r) #shuffles r in place
print (r)
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
1
import random
chars = ['s', 'p', 'a', 'm']

random.shuffle(chars)
for char in chars:
    print char

This will randomize the list in-place though.

siebz0r
  • 18,867
  • 14
  • 64
  • 107
1
list = [1, 6, 7]
random.shuffle(list)
for k in range(1,len(list)+1):
    print list[k]
0

Here is a working version of your code.

import random
chars = [1, 6, 7, 8, 5.6, 3]
for k in range(1, len(chars)+1):
    thechar = random.choice(chars)
    place = chars.index(thechar)
    print thechar
    chars[place:place+1]=''

When you do the random.choice twice in print random.choice(chars) and in chars[random.choice(chars)] = '', it is picking another random choice from chars. Instead, set the random.choice to something so that you can call it later. Even if you had done that, when you set chars[random.choice(chars)] = '', it just sets that spot to '', it doesn't delete it. So if your random.choice was 5.6, the chars list would just become [1, 6, 7, 8, '', 3], not [1, 6, 7, 8, 3]. To do that, you have to save the place of the char, and do chars[place:place+1]. And finally, due to the for syntax, you have to do the len(chars)+1, so that it only goes to len(chars).

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

See the following link: Shuffle and re shuffle list in python?

from random import shuffle

x = [[i] for i in range(10)]
shuffle(x)

print x
Community
  • 1
  • 1
Nabin
  • 11,216
  • 8
  • 63
  • 98