Steven D'Aprano wrote: > On Sat, 18 Sep 2010 07:13:13 pm Peter Otten wrote: > >> You should never iterate over a list or dictionary and add or remove >> items to it at the same time. That is a recipe for disaster even if >> it doesn't fail explicitly. > > That's a bit strong. It's quite possible to modify lists safely and > correctly while iterating over them with a little bit of care.
You're of course not the intended audience of my advice. > You know, for decades people were able to program in languages like C > and Pascal and assembly, often on machines with tiny amounts of memory. > When your machine has 64K of memory, and the OS and application uses > half of it, you don't have the luxury of making a copy of a 20K list > before modifying it. Back when I was a lad, we learned how to modify > lists in place. It isn't hard. *wink* When you do that you are usually operating on an abstraction level below Python. > Even in Python, it is sometimes necessary to modify lists and even dicts > in place while iterating over them. 98% of the time, making a copy is > faster, simpler and more efficient, but learning how to safely modify > data structures in place is a valuable skill to have. If you have a huge list that you can only modify in place you may have chosen the wrong data structure. > But I'm just talking about general principles here. In most cases, stick > to Peter's advice to make a copy. Hey, I can agree with that ;) Peter _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor