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.

@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.

Follow

@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.

· · Web · 0 · 0 · 1
Sign in to participate in the conversation
Mastodon

Server run by the main developers of the project 🐘 It is not focused on any particular niche interest - everyone is welcome as long as you follow our code of conduct!