Today I Learned: Pretty python last

2026/05/30

I’ve always found python’s functional list processing capabilities to be quite annoying:

So whenver I’m working with python for some project and I end up deciding on using functional programming to describe my transformations, I always keep my expectations quite low.

However, today I’ve found something that genuinely made me think “impressive!” when dealing with iterators in python. In short, I needed to get the last element of an iterator. I could just do last = list(iterator)[-1], but turning the whole thing into a list makes me unconfortable (I know, worrying about performance and python aren’t two things one should do at the same time, but I wouldn’t feel ok unless I’ve learned how to do this properly). Instead, turns out that python has some since syntax for unpacking lists when doing destructuring:

*_, last = iterator
 

Simple, no need to turn the whole thing into a list, works just great! You can also use a variable name instead of _ if you want to save the content of the rest of the list. It’s like specialized subset of pattern matching, if you think about it.