On 03/12/2010 1.32, Steven D'Aprano wrote:
Back in Ancient Days when dinosaurs walked the earth, and I programmed in Pascal, computers didn't have much memory, and were slow. Consequently it wasn't practical to make a copy of a list if you wanted to delete a few items. The only practical way to modify lists was to modify them in place, and if you needed to delete items, you had to work backwards. It took me a while to break myself of the habit of doing this:for i in range(len(mylist)-1, -1, -1): if mylist[i] == "something": del mylist[i] (Note that you only need to work backwards if you're *deleting* entries, not if you replace them with something else.) This is still a useful technique to have in your toolbox, but generally speaking the above is better written as: mylist = [x for x in mylist if x != "something"]
Up to this point, I share experiences and solution. But the next point did thrill me:
If you really need to modify the list in place, and not just re-bind the name "mylist" to the new list, then one tiny change will do it: mylist[:] = [x for x in mylist if x != "something"]
I thought mylist[:] was a copy of mylist, and the two lines above would generate exactly the same code! Is this a special optimization by the Python interpreter, or is it just a mistake in my understanding of the slice operator? ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 10.0.1170 / Database dei virus: 426/3313 - Data di rilascio: 13/12/2010 _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
