Python 3 Iterable Unpacking Catch-all

I’m one of those terrible people that still haven’t switched over to using Python3 …just yet. But one thing that pleasantly surprised me recently was learning of the “new” starred expression catch-all that can be used when unpacking iterables. This lets you use up to one starred expression to receive the rest of the items of an iterable during an unpacking assignment.

full_name = "Steven W J Brown"

#python2
names             = full_name.split()                # ['Steven', 'W', 'J', 'Brown']
first, last       = names[0], names[-1]              # 2.A: ignore middle names
first, mids, last = names[0], names[1:-1], names[-1] # 2.B: store middle names

#python3, 
first, *_, last    = full_name.split() # 3.A: ignore middle names
first, *mids, last = full_name.split() # 3.B: store middle names

It’s easy to read, eliminates the need for an intermediary variable and makes the code cleaner. And it can be used in loops. More details here: PEP 3132. Love it.

I really have to start re-configuring my environments for python3….


Information about this entry:

Leave a Comment

Allowed code: <a href="" title="">, <abbr title="">, <acronym title="">, <b>, <blockquote cite="">, <cite>, <code>, <del datetime="">, <em>, <i>, <q cite="">, <s>, <strike>, <strong>