Is there a need for range(len(a))?

后端 未结 11 684
执念已碎
执念已碎 2020-12-02 05:05

One frequently finds expressions of this type in python questions on SO. Either for just accessing all items of the iterable

for i in range(len(a)):
    prin         


        
11条回答
  •  萌比男神i
    2020-12-02 05:48

    Very simple example:

    def loadById(self, id):
        if id in range(len(self.itemList)):
            self.load(self.itemList[id])
    

    I can't think of a solution that does not use the range-len composition quickly.

    But probably instead this should be done with try .. except to stay pythonic i guess..

提交回复
热议问题