4 ms·
Python is my favorite language, but finding a way to iterate over a list while changing the list kills me. I remember there is a good reason for Python's behavi
by mbenjaminsmith 16y ago
Python is my favorite language, but finding a way to iterate over a list while changing the list kills me. I remember there is a good reason for Python's behavior but it always surprises me how non-intuitve a solution is.
- Luyt 16y agoPython is not unique in this regard. Consider a functional approach, where you leave the original list intact and construct a changed one.
- koenigdavidmj 16y agoList comprehensions or map are the way that a Pythonista would do this: [transform(x) for x in my_list] map(transform, my_list)
- conesus 16y agoIf iterating over a list, try iterating backwards. That way you can delete items from the list without effect on iterator position. This doesn't work on dicts, of course, but this way you can delete in-place without creating a copy data structure.