Python 空列表上的for循环实际会花费时间/资源吗?

Python 空列表上的for循环实际会花费时间/资源吗?,python,for-loop,resources,Python,For Loop,Resources,这并不是一个特定于任何代码的问题,也不是我遇到的问题,但出于知识的考虑,我想知道 比如,我有以下代码: # list1 and list2 are determinied off the screen if len(list1) > 0: cycler = list1 elif len(list2) > 1: cycler = list2 else: cycler = [] for id in cycler: t = Thing._by_id(id)

这并不是一个特定于任何代码的问题,也不是我遇到的问题,但出于知识的考虑,我想知道

比如,我有以下代码:

# list1 and list2 are determinied off the screen
if len(list1) > 0:
    cycler = list1
elif len(list2) > 1:
    cycler = list2
else:
    cycler = []

for id in cycler:
    t = Thing._by_id(id)
    # a lot of stuff done with t

在第三种情况下,
cycler=[]
,是否有任何资源/时间用于for循环,或者for循环是否立即中断?我一点也不担心这个,事实上,我在一个函数中有这个函数,它
return
在else子句中,我只是好奇。

不是我的代码,但是如果我们看这里,我们会看到时间被用来创建这个“空列表”


就实际遍历列表而言,是的,这也会消耗资源。解释器必须至少知道列表是空的,所以它必须进入内存位置才能看到它是空的。

如果你问Python解释器是否能够通过完全跳过循环进行优化,我认为答案是否定的。如果你在空列表上查看字节码进行迭代,所有循环设置步骤仍然完成,并为循环内的代码生成字节码(尽管不会实际执行):


使用迭代协议。调用列表的
\uuu iter\uu
方法,该方法返回一个迭代器
id
获取迭代器返回的值。\uuuu next\uuuu()
,它在到达列表末尾时立即引发
StopIteration
,即在第一次调用时感谢
-m timeit
% python -mtimeit  "l=[]"
10000000 loops, best of 3: 0.0711 usec per loop

% python -mtimeit  "l=list()"
1000000 loops, best of 3: 0.297 usec per loop
import dis

def run_empty_loop():
    a = []
    for item in a:
        x = 1 + 1


dis.dis(run_empty_loop)
  2           0 BUILD_LIST               0
              3 STORE_FAST               0 (a)

  3           6 SETUP_LOOP              20 (to 29)
              9 LOAD_FAST                0 (a)
             12 GET_ITER
        >>   13 FOR_ITER                12 (to 28)
             16 STORE_FAST               1 (item)

  4          19 LOAD_CONST               2 (2)
             22 STORE_FAST               2 (x)
             25 JUMP_ABSOLUTE           13
        >>   28 POP_BLOCK
        >>   29 LOAD_CONST               0 (None)
             32 RETURN_VALUE