walk through a python list backward with bitwise negation:

>>> L = ["first", "second", "third", "second-last", "last"]
>>> L[0]
'first'
>>> L[~0]
'last'
>>> L[~1]
'second-last'
>>> L[~2]
'third'

@danso That's pretty great. I'd worry about using it in a shared codebase due to familiarity, but I wonder how much it helps reason about slicing and avoid off by one errors.

Aside: negative indexing seems like just about the most justified and high-reward sugar a language can have.

Follow

@badtuple i have not decided whether i'm seriously going to start doing it! it's cute and playful, but i would definitely be stunned if i saw this in actual code for the first time.

@danso I think the actual use of ~ in this context is mostly familiarity, like the !! truthiness trick. My biggest worry is that in places like slices and ranges it trips up the already confusing intuition around whether something is inclusive or exclusive.

It might defeat the point since it loses brevity, but you could get rid of the familiarity tax with a function.

fromEnd = lambda x: ~x
L[fromEnd(2)]

Eh, I like that less now that I've typed it out. But posting anyway for good measure.

Sign in to participate in the conversation
Fosstodon

Fosstodon is an English speaking Mastodon instance that is open to anyone who is interested in technology; particularly free & open source software.