Thursday, March 22, 2018

The Zen of Empty Lists

"There should be one-- and preferably only one --obvious way to do it". One of the many philosophies that has earned Python its acclaim.

But while the Zen of Python limits on the number of obvious ways, the Zen of Python says nothing about the boundless freedom of unobvious ways.

Let's empty a list named bucket.

The most obvious way is to simply not. 99 times out of 100, you want to assign a new empty list rather than mutating the old.
bucket = []
But let's say you really wanted to empty it, well the clearest way is clear:
bucket.clear()
But even the docs say this is equivalent to:
del bucket[:]
I guess that's crossing the obvious line. Of course, it may be more obvious than Norvig's "dumbell" operator:
bucket[:]=[]
Actually the slice assignment can take any iterable, so our list can lift plates of many shapes:
bucket[:]={}
If you don't want your list getting ripped and/or cut, maybe keep it warm with Norvig's ski hat:
bucket *=0
The ski hat is of particular interest because it's using a very obvious list feature, much more commonly used than list.clear(). Nobody would bat an eye at:
bucket = [0, 1, 2, 3] * 2
# bucket = [0, 1, 2, 3, 0, 1, 2, 3]
If you multiply any list by 0, you make a new list of length 0. Bizarrely, this is actually true of any multiplier less than 0, too.
bucket *= -3
# bucket = []
Safe to say we are deep in the territory of the unobvious. Is there a syntax we might meditate on to take us further?

8 comments:

  1. There's also

    bucket *= False

    just to complicate things further.

    ReplyDelete
    Replies
    1. I think that's just because False is the equivalent of 0 in python? So, I guess it doesn't complicate it much.

      Delete
    2. I'm not sure about the answer, but you certainly can't say that "False is the equivalent of 0 in python". You could say that in languages like C, or loosely typed language like php.

      Delete
    3. In Python, `False == 0`, but `False is not 0`. Because `issubclass(bool, int)`, False and True act like 0 and 1 in a numerical context.

      Delete
  2. {0: 'bar', False: 'bar', 1.0: 'bar'}

    ReplyDelete
  3. I discovered your site ideal for me. It consists of wonderful and useful posts. I've read many of them and also got so much from them. In my experience, you do the truly amazing.Truly i'm impressed out of this publish 먹튀검증

    ReplyDelete
  4. Choosing a relevant template for your site is so important. I recently visited this website and it had such a good business template. It provided marketing essay example, and there were proper widgets for each topic. Like, business management dissertation topics were in a widget, similarly, marketing topics were all together. I was really impressed by the work.

    ReplyDelete