Discussion about this post

User's avatar
Youven's avatar

Zip(**array1,**array2) is a great one too

Expand full comment
Wyrd Smythe's avatar

Lotta old friends there. One thing to keep in mind about #1 when writing your own classes that implement __reversed__ as well as __getitem__ is that obj[::-1] obviously invokes the latter while reversed(obj) returns the former. And that the latter returns an item, obj[which], or a list of items, obj[range], whereas reversed(obj) returns a reversed generator object. That bit me once when I was implementing a "byte string" class.

Also, #6 only works if the outer list contains *only* unnested sub-lists. It fails if any item in the outer list isn't iterable. And it doesn't flatten sub-sub-lists. Handy in the right use case, though. They all are! I use #10 constantly, often for kwargs:

eggs = kwargs['spam'] if 'spam' in kwargs else 'bacon'

So often that I made:

KWARG = lambda nam,kw,typ,dflt: typ(kw[nam]) if nam in kw else dflt

To let me say:

eggs = KWARG('spam', 'bacon', str, kwargs)

cake = KWARG('cake', 42, int, kwargs)

Because I hated the error-prone double-entry, especially the quoted name.

Expand full comment

No posts