Which is the most efficient way to iterate through a list in python?

后端 未结 4 1106
暗喜
暗喜 2020-12-16 10:49

Say I have a list of items:

x = [1, 2, 3, 4, 5]

I need to perform some functions for each of these items. In a certain case, I need to retu

4条回答
  •  旧时难觅i
    2020-12-16 11:41

    Obviously for i in range(len(list)): will be slower - in python 2, it's equivalent to this:

    list2 = range(len(list))
    
    for i in list2:
        ...
    

    If that were faster, then this would be even faster, right?

    list2 = range(len(list))
    list3 = range(len(list2))
    list4 = range(len(list3))
    
    for i in list4:
        ...
    

提交回复
热议问题