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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are not permitted to remove elements from the list while iterating over it using a
forloop.The best way to rewrite the code depends on what it is you’re trying to do.
For example, your code is equivalent to:
Alternatively, you could use a
whileloop:You could copy every element that doesn’t match the condition into a second list:
Alternatively, you could use
filteror a list comprehension and assign the result back toa:or
where
...stands for the condition that you need to check.