Dear Pythonites

I am looking for a more elegant solution to a piece of code that is too unwieldy and reptitive. The purpose of the code is for a new addition to a list to check whether it is a duplicate of a list element already a member of that list, and if so to regenerate itself randomly and to perform the same check again until such time as it is unique.
For example, this is what I am currently doing:


=============code block ========================

   # generate unique numbers and append to list
   nmbr01 = random.randrange( 1, 20 )
   nmbr_list.append( nmbr01 )

   nmbr02 = random.randrange( 1, 20 )
   # check for duplicates and re-generate a number if needed
   while nmbr02 in nmbr_list:
       nmbr02 = random.randrange( 1, 20 )
   nmbr_list.append( nmbr02 )

   nmbr03 = random.randrange( 1, 20 )
   while nmbr03 in nmbr_list:
       nmbr03 = random.randrange( 1, 20 )
   nmbr.append( nmbr03 )

================================================

This method works, but increasing the numbers to be appended makes the code excessively long. I can't see anything in list methods that seems to do the trick, so anybody want to make a suggestion please?

TIA
/j
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to