Dec-18-2020, 09:25 PM
If you modify an object while iterating over it, it can cause problems.
Either iterate over a copy of it, or copy the data you do need and don't copy the rest. Examples:
Iterate over a copy:
Either iterate over a copy of it, or copy the data you do need and don't copy the rest. Examples:
Iterate over a copy:
nr = 9 my_list = [0,5,6,7,6,9,9,1,9] for i in my_list[:]: if i is not nr: my_list.remove(i) print(my_list)Pull out the data you want, and overwrite the old reference
nr = 9 my_list = [0,5,6,7,6,9,9,1,9] my_list = [x for x in my_list if x == nr] print(my_list)