[Tutor] Creating lists with definite (n) items without repetitions

Peter Otten __peter__ at web.de
Thu Sep 3 17:39:43 CEST 2015


Marcus Lütolf wrote:

> as a newcomber I want to create a set of lists containing n items, for
> example n = 3:  (['a','b','c'], ['a','d','e'].......).
> The sequence of items in each list should be different. If the letters
> 'a'........'z' are used and n = 3 there is a maximum of 301 lists.
> The following code works only for lists containing 1 item:
> 
> import random
> list = ['a', 'b', 'c', 'd',....... 'z']
> random.shuffle(list)
> for x in list:
>      print x
> 
> how can I solve my task wit n items ?

At first I thought you might want itertools.combinations()

>>> import string, itertools
>>> for t in itertools.combinations(string.ascii_lowercase, 3):
...     print t # list(t) if you actually need a list
... 
('a', 'b', 'c')
('a', 'b', 'd')
('a', 'b', 'e')
('a', 'b', 'f')
('a', 'b', 'g')
[snip]

but that gives

>>> sum(1 for t in itertools.combinations(string.ascii_lowercase, 3))
2600

2600 different tuples

Can you give more details on how to pick the lists?



More information about the Tutor mailing list