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

Martin A. Brown martin at linux-ip.net
Thu Sep 3 19:43:55 CEST 2015


Greetings Marcus,

Peter Otten has also responded, recommending itertools.  I think 
both he and I are not sure how you wish to generate your result list 
(or lists).  But, I have a comment or two.

> dear pythonistats
> 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']

I would recommend against using the name "list".  The name list is a 
Python builtin which creates a list().  Try it at the interactive 
prompt:

   >>> list()
   []

So, I'd recommend changing that name to "l" or "result" or something 
like that.

> random.shuffle(list)
> for x in list:
>     print x
>
> how can I solve my task wit n items ?
> Thank you for help, Marcus.

You are using random.  Do you want n randomly selected items from 
the input list?  The random module provides random.sample() to 
select n items from a sequence.

If so, try this out at the intercative prompt.  Perhaps this is what 
you are looking for?

   >>> import random
   >>> import string
   >>> l = list(string.lowercase)
   >>> random.sample(l, 7)
   ['z', 'h', 'e', 'n', 'c', 'f', 'r']

Best of luck,

-Martin

--
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list