l1=list(range(10))
for i in range(len(l1)):
l1.pop()
print(i,l1,l1[-1])
#
0 [0, 1, 2, 3, 4, 5, 6, 7, 8] 8
1 [0, 1, 2, 3, 4, 5, 6, 7] 7
2 [0, 1, 2, 3, 4, 5, 6] 6
3 [0, 1, 2, 3, 4, 5] 5
4 [0, 1, 2, 3, 4] 4
5 [0, 1, 2, 3] 3
6 [0, 1, 2] 2
7 [0, 1] 1
8 [0] 0
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-41-ca6fe5f266d2> in <module>
2 for i in range(len(l1)):
3 l1.pop()
----> 4 print(i,l1,l1[-1])
IndexError: list index out of range
l1=list(range(10))
for i in l1:
l1.pop()
print(i,l1,l1[-1])
#
0 [0, 1, 2, 3, 4, 5, 6, 7, 8] 8
1 [0, 1, 2, 3, 4, 5, 6, 7] 7
2 [0, 1, 2, 3, 4, 5, 6] 6
3 [0, 1, 2, 3, 4, 5] 5
4 [0, 1, 2, 3, 4] 4
for i in 的实质,后面是带iterable的,当这个可迭代结束后,for就结束了。
而i,他属于从索引0开始顺序遍历的iterable对应索引位置上的数值。
如果这不好理解的话,那么来个另类的操作,for的时候,增加迭代目标的长度
l1=list(range(10))
for i in l1:
l1.append(i*-1)
print(i,l1)
if len(l1)==30:break
#
0 [