1. 程式人生 > >python tricks

python tricks

A pitfall that may be encountered when removing an element from a list in a for loop in python

example:

nums = [1, 2, 3, 4, 5]
for i in nums:
    if i == 3:
        nums.remove(i)
    print(i)

# result:
# 1
# 2
# 3
# 5
# Solution:
temp = []
nums = [1, 2, 3, 4, 5]
for i in nums:
    if not
i == 3: temp.append(i) nums = temp for i in nums: print(i)