How to remove list elements in a for loop in Pytho

2019-01-01 07:37发布

This question already has an answer here:

I have a list

a = ["a", "b", "c", "d", "e"]

I want to remove elements in this list in a for loop like below:

for item in a:
    print item
    a.remove(item)

But it doesn't work. What can I do?

标签: python list
7条回答
与风俱净
2楼-- · 2019-01-01 07:44

Remove function removes the first element in the list (0th index element). In the first iteration of your for loop you start with index number 0, print it. As you move to index number 1 you no longer have 'a' at index location 0 but you have 'b' instead. So what you get will be 'c'. So this code piece will print list elements with even index numbers only.

查看更多
登录 后发表回答