This is a well-documented behaviour in Python, that you aren’t supposed to modify the list being iterated through. Try this instead:
for i in x[:]:
x.remove(i)
The [:]
returns a “slice” of x
, which happens to contain all its elements, and is thus effectively a copy of x
.
More Related Contents:
- I have a list of file names and I need to be able to count how many of the same file gets repeated for each file name [closed]
- What does “list comprehension” and similar mean? How does it work and how can I use it?
- What’s the difference between lists and tuples?
- How to remove list elements in a for loop in Python? [duplicate]
- Iterate over all pairs of consecutive items in a list [duplicate]
- How Big can a Python List Get?
- Flatten an irregular list of lists
- Python: Removing list element while iterating over list [duplicate]
- Converting a String to a List of Words?
- How to perform element-wise multiplication of two lists?
- Check if something is (not) in a list in Python
- elegant find sub-list in list
- How to group a list of tuples/objects by similar index/attribute in python?
- How to force a list to a fixed size?
- What is the inverse function of zip in python? [duplicate]
- Pandas expand rows from list data available in column
- How to check if an object is a list or tuple (but not string)?
- How to remove all duplicate items from a list [duplicate]
- Unpack list to variables
- Python using enumerate inside list comprehension
- How to find common elements in list of lists?
- How to convert a string list into an integer in python [duplicate]
- Convert list of strings to dictionary
- Most efficient way for a lookup/search in a huge list (python)
- Sort list of strings by a part of the string
- How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
- How can I partition (split up, divide) a list based on a condition?
- Python: Rename duplicates in list with progressive numbers without sorting list
- Optimal method to find the max of sublist items within list
- In what case would I use a tuple as a dictionary key? [closed]