Mohammad ElNesr Mohammad ElNesr - 1 month ago 8
Python Question

Is it always wrong to modify a list while iterating on it? and why?

I have a list containing my data, in the following form:

data = [[[1, 3, 4, 5, 7], [A, B, C]],
[[2, 3, 8, 2, 9], [F, C, C]],
[[6, 3, 1, 3, 1], [F, E, D]],
[[2, 3, 7, 0, 3], [F, C, F]],
...
[[0, 3, 3, 4, 5], [F, B, A]]]


In my program, I would check if there is a column that has a fixed value (like the second column that contains only 3s. If found, I should remove it from the data. One of the solutions that we could iterate over the list and remove this column element by element. with the following code:

for data_line in data:
del data_line [0][1]


Is this OK or not? Can this cause instability or any other problem?
Please explain..

Thanks in advance

Summary of solutions

Thanks for all who contributed to this question, to summarize the valuable contributions below we can say:

It is OK to modify the contents of the list you are iterating over it, but not to remove elements of it, i.e. wherever the modification does not change the length of the MAIN list, then no problem.

Answer

You can modify properties of the elements of the list while iterating, but it is quite inadvisable to modify the list membership itself. You are doing the former, so no worries.

Comments