is there a shorter way to write this

Vlastimil Brom vlastimil.brom at gmail.com
Thu Jan 29 15:35:46 CET 2009


2009/1/29 garywood <pythonsky at sky.com>:
> I had a task in a book to pick 5 items from a list of 26 ensuring the items
> are not repeated
>
>
> import random
> list = ['a','b','c','d','e','f','g','h','i','j','k','l','m',
>         'n','o','p','q','r','s','t','u','v','w','x','y','z']
> word = ' '
> a = random.choice(list)
> list.remove(a)
> b = random.choice(list)
> list.remove(b)
> c = random.choice(list)
> list.remove(c)
> d = random.choice(list)
> list.remove(d)
> e = random.choice(list)
> list.remove(e)
> word = a + b + c + d + e
> print (word)
> print(list)
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
There are probably several ways to do that, e.g.:

>>> lst = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
>>> randomized_list = lst[:]
>>> random.shuffle(randomized_list)
>>> randomized_list[:5]
['n', 'p', 'e', 'f', 'y']
>>>

(better not name a variable like a builtin - list)

hth,
  vbr



More information about the Python-list mailing list