Monday, November 24, 2008

Python - list clearing?!!

Today's trick question: How do you clear a list in python?

Not by .clear(), as you do with other python containers set or dicts (or _any_ in C++/Java/whatnot).

Nonono, you assign the entire slice of the list to the empty list, or delete the whole slice!

mylist[:] = []
del mylist[:]


.. .. .. .. Arrghh!!!!

Why do I have to learn the slice syntax, and the fact that there is a slice of the whole pie, and that I can assign a list to a slice, just to clear the list?!

Appending, concatenating and clearing are simple & common ops, that should be represented clearly and simply. Slicing is advanced, and when I want to do slicing, I read up on it, but I should need it for that. It's like requiring someone to learn discrete integration just to do addition; valid but only correct in the very bad technically-correct kind of way.

(And no, just assigning the empty list to it does not work, as that rebinds the name, it does not change the original list. I have no issue with that, as it's all pointers/references everywhere.)

Apparently, they haven't fixed this in Py3k either.

Looking through forums where this appear every month since Python was first created, the sentiment seems to be that since you can do it with slicing, there's no need for another way to do it!

I began to understand why people feel that the python community is regarded as a bit 'frosty' and cold.

I still like python a lot, but ... Bah!
Post a Comment