[Tutor] Deleted dictionary length not reporting
Steven D'Aprano
steve at pearwood.info
Wed Jul 17 05:42:40 CEST 2013
On 17/07/13 12:55, Jim Mooney wrote:
> so I'm going back to just popping used items
> from a list, which was dirt-simple.
And also dirt-simple to get wrong, and inefficient as well.
list.pop has its uses, but I strongly recommend that you learn more "Pythonic" techniques that don't rely on modifying the list unnecessarily. For example, instead of something like this:
while some_list:
process(some_list[0]) # work on the first item
some_list.pop(0) # and then drop it
this will be *much* more efficient, as well as easier to understand:
for item in some_list:
process(item)
If you really need to clear the list, it's more efficient to clear it all at once at the end than to clear it item-by-item:
some_list[:] = []
Here's a question for you, to test your Python knowledge:
Assuming that some_list is already a list, what's the difference between these two lines, and under what circumstances why would you want to use the second one?
some_list = []
some_list[:] = []
(Tutors, please leave this one for the beginners to answer.)
--
Steven
More information about the Tutor
mailing list