Just saw a post on LinkedIn warning against in Python modifying a list while iterating over it.
Good advice: the results of doing so are indeed surprising to the inexperienced.
Example:
items = [ 1, 2, 2, 3, 4 ]
for item in items:
if item == 2:
items.remove(item)
print(items)
[1, 2, 3, 4]
Java and C# throw an exception in such cases.
package september;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class UpdItList {
public static void main(String[] args) {
List<Integer> items = new ArrayList<Integer>(Arrays.asList(1, 2, 2, 3, 4 ));
for(Integer item : items) {
if(item == 2) {
items.remove(item);
}
}
System.out.println(items);
}
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013)
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967)
at september.UpdItList.main(UpdItList.java:10)
using System;
using System.Collections.Generic;
namespace UpdItList
{
public class Program
{
public static void Main(string[] args)
{
IList<int> items = new List<int> { 1, 2, 2, 3, 4 };
foreach(int item in items)
{
if(item == 2)
{
items.Remove(item);
}
}
Console.WriteLine(string.Join(",", items));
Console.ReadKey();
}
}
}
System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource) at System.Collections.Generic.List`1.Enumerator.MoveNextRare() at System.Collections.Generic.List`1.Enumerator.MoveNext() at UpdItList.Program.Main(String[] args) in c:\IDEProjects\SharpDevelop5\UpdItList\UpdItList\Program.cs:line 11
I very much prefer the exception.