r/Python • • Nov 14 '17

Senior Python Programmers, what tricks do you want to impart to us young guns?

Like basic looping, performance improvement, etc.

1.3k Upvotes

629 comments sorted by

View all comments

Show parent comments

3

u/masklinn Nov 14 '17

Values get named, much more comprehensible than having to know what the fuck [1] corresponds to.

Alternative: namedtuples or proper objects (attrs is good for cheaply creating your own types).

1

u/[deleted] Nov 14 '17

I meant is there any benefit between that approach and going;

first, second = sequence_var[:2]

Destructuring is fantastic in many contexts, just hadn't seen it applied in this approach.

3

u/masklinn Nov 14 '17
  1. proper unpacking works with any iterable, slicing only works with, well, sliceable collections

  2. Python 3's extended unpacking lets you pick bits at the end e.g. first, second, *_, last = seq, and of course you can name the intermediate seq if you want (first, second, *mid, last)

  3. unlikely to have any effect but the builtin is a single µop (UNPACK_EX) versus 3 (BUILD_SLICE; BINARY_SUBSCR; UNPACK_SEQUENCE)