Hi, I am trying to get Python to pick random letters from a given list.
However I don't want any repetitions, I just can't seem to figure out how to skip
on letters already chose.
Any help would be greatly appreciated.
Here is what I have so far

let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]

import random

for i in range(3):
    pos = random.randint(0,6)
    letter = let[pos]
    print letter,

You could always just add del let[ pos ] after that letter has been printed, thus deleting that letter from the list. It'll never be selected again.

I've tried that but I get an error saying that the list index is out of range, I'm guessing because everytime you delete a letter, the range changes.

there is also random.choice(let) which would choose a random element of your list instead of choosing a random index. After that, use del let[pos].

I've tried that but I get an error saying that the list index is out of range, I'm guessing because everytime you delete a letter, the range changes.

Yes, but it's easy to fix. Here's the updated code:

let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]

import random

for i in range(3):
    pos = random.randint(0,len(let))
    letter = let[pos]
    print letter,

All I did was change the line with the random function so that it went from 0 to the length of the array, therefore making sure indices that don't exist anymore don't get called.

I tried your suggestion and I am gettin the error list indices must be integers.

this one just swaps the list elements

import random

let = list("abcdefg")

n = len(let)
for j in xrange(3):
    n -= 1
    i = random.randint(0, n)
    print let[i],
    let[i], let[n] = let[n], let[i]
print

random.sample() may be what you are looking for.

>>> let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
>>> random.sample(let,len(let))
['a', 'd', 'g', 'b', 'c', 'f', 'e']
>>> random.sample(let,3)
['d', 'e', 'b']
>>> random.sample(let,3)
['a', 'f', 'e']
>>>

One more way for the fun of it:

import random

let = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]
random.shuffle(let)

while len(let):
    print let.pop()

Thanks guys, I have solved the problem!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.