Search code examples
pythonlisttuplesiterable-unpacking

How to pick certain elements of x-tuple returned by a function?


I am a newbie to Python. Consider the function str.partition() which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?

I can currently do either:

# Introduces "part1" variable, which is useless
(part0, part1, part2) = str.partition(' ')

Or:

# Multiple calls and statements, again redundancy
part0 = str.partition(' ')[0]
part2 = str.partition(' ')[2]

I would like to be able to do something like this, but cannot:

(part0, , part2) = str.partition(' ')
# Or:
(part0, part2)   = str.partition(' ')[0, 2]

Solution

  • Underscore is often used as a name for stuff you do not need, so something like this would work:

    part0, _, part2 = str.partition(' ')
    

    In this particular case, you could do this, but it isn't a pretty solution:

    part0, part2 = str.partition(' ')[::2]
    

    A more esoteric solution:

    from operator import itemgetter
    part0, part2 = itemgetter(0, 2)(str.partition(' '))