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)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐