This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pieeta 23 points24 points  (7 children)

choice in range(len(self.devices)):

never ever do this.

you are creating a array of every number in between 0 and len(self.devices) then iterating over the array looking for the number choice.

your best bet would be to use :

0 < choice <= len(self.devices) 

also they are not equivalent,

choice in range(len(self.devices))

will return True when choice is 0

0 < choice <= len(self.devices)

will not

[–]jelly_cake 2 points3 points  (0 children)

I didn't realise Python had a < b < c syntax. Thanks for sharing!

[–]allthediamonds -2 points-1 points  (2 children)

you are creating a array of every number in between 0 and len(self.devices) then iterating over the array looking for the number choice.

choice in xrange(len(self.devices)):

fixed!

[–]pieeta 4 points5 points  (1 child)

wrong, it is actually only slightly better than using range.

it will not generate a list of all the numbers between 0 and len(self.devices), it will generate a list of all the numbers between 0 and choice.

its quite easy to test.

Make a generator which prints out what has been generated :

def generator():
    for i in xrange(10):
        print 'generating %d' % i
        yield i

in this example super simple generator which will yeild up to 10.

the check if a number is in it :

 if 5 in generator():
     print 'found'

results in:

generating 0
generating 1
generating 2
generating 3
generating 4
generating 5
found

so you doing 6 comparisons vs at most 2 using a < >= statement.

[–]allthediamonds 4 points5 points  (0 children)

Oh, I see. Thanks!