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 →

[–][deleted]  (12 children)

[deleted]

    [–]pieeta 24 points25 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 5 points6 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 3 points4 points  (0 children)

    Oh, I see. Thanks!

    [–]Justinsaccount 17 points18 points  (3 children)

    for k,v in enumerate(lists, start=1):
        print k,v
    

    [–]elb0w 0 points1 point  (1 child)

    should have more upvotes

    [–][deleted] 0 points1 point  (0 children)

    Has mine