generate all combinations of a list (with variable output length)

Cliff Wells logiplexsoftware at earthlink.net
Fri Jun 28 22:13:05 CEST 2002


On Fri, 28 Jun 2002 21:52:13 +0200
thomas wrote:

> hi,
> 
> i'm looking for a way to generate all possible combinations of all items 
> in a list. list = ["A","D","$","5","R"]
> 
> but i also want it to use one item several times or not at all and in no 
> particular order. the length of the string is 1-10. so a possible output 
> would be:
> 
> DD$
> A5RD$D555
> A
> 5RR$$A
> DRRR55$5$A
> ...

How about:

import random

l = ["A","D","$","5","R"]
randomList = [l[random.randrange(0, len(l))] for i in range(random.randrange(1,
len(l) + 1))]

This assumes you want at least one item in the list.  Also, please note that
using "list" as a variable name is bad as it is the name of a built-in type.

Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308





More information about the Python-list mailing list