天天看点

python切片数组越界?

1 .在对list进行切片时,如x[9:12],若len(x)=10,只会返回x[9],而不会像其他语言直接数组越界错误。

x=[i for i in range(10)]
print(x)
for i in range(0,10,3):
    print(x[i:i+3])      

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[0, 1, 2]

[3, 4, 5]

[6, 7, 8]

[9]

2 .切片返回的仍然是list对象,而访问元素返回的是值。

x=[i for i in range(10)]

print(x[10:11])#切片[x[10]]为空
print(x[10])#取值x[10]报错      

[]

Traceback (most recent call last):

File “E:/Code/PycharmProjects/test/test01.py”, line 4, in

print(x[10])

IndexError: list index out of range

python切片数组越界?额,不存在的。