[Tutor] Print record x in a file

Kent Johnson kent37 at tds.net
Sun Jan 23 13:46:08 CET 2005


Jacob S. wrote:
>> import random
>> #the above gives the program the ability to get a
>> #pseudo random number
>> file = open('test.rantxt')
>> listcontents = file.readlines()
>> #gives you the file as a list of records or it did on
>> #(assuming each line is a record)
>> file.close()
>> lenoflist = len(listcontents)-1
>> #find the length of the list and take one of because
>> computers count from 0
> 
> 
> Yes, but len returns counting from 1.
> Anyway, you would have to add one to correct that anyway, wouldn't you?
> If randrange is start <= x *<=* end, then you don't have to add one, you
> just use the length.
> If randrange is start<= x < end like __builtin__ range, you have to put
> randrange(1,lenoflist+1)
> 
>> x = random.randrange(0,lenoflist)
> 
> 
> I would use randint because list indices need to be integers -- unless of
> course I mistaken and
> randrange returns an integer also. (But that would be repetitive to have to
> functions do the same thing)

A quick check of the module docs (Jacob, do you know where to find the docs?) gives

randrange(  	[start,] stop[, step])
     Return a randomly selected element from range(start, stop, step). This is equivalent to 
choice(range(start, stop, step)), but doesn't actually build a range object. New in version 1.5.2.

So the limits on randrange() are the same as for range() - it is start <= x < stop. And the returned 
value is an integer.

  Since len(listcontents) is one greater than the largest valid index of listcontents, the correct 
use of randrange() for this problem is
   x = random.randrange(0, len(listcontents))

> 
>> print listcontents[x]
> 
> 
> HTH,
> Jacob
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list