Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Xử lý exception list rỗng (empty list) trong Python

List truy cập bằng index 0 đến length-1. Index vượt range → IndexError.

Ví dụ: Pop cho đến khi rỗng

a = [1, 2, 3]
while True:
    try:
        b = a.pop()
        print(b)
    except IndexError:
        break

Output

3
2
1

Cách tốt hơn: Check trước

a = [1, 2, 3]
while a:  # List rỗng = False
    print(a.pop())

Hoặc dùng for loop

for item in reversed(a):
    print(item)

Nguyên tắc: "Easier to Ask Forgiveness than Permission" (EAFP) dùng try/except, hoặc "Look Before You Leap" (LBYL) check condition trước. Với list rỗng, check if list: hoặc while list: pythonic hơn.