Question

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]
Was it helpful?

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(' '))

OTHER TIPS

Correct, you can not take several ad hoc elements out of a list of tuple in one go.

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

Is the way to go. Don't worry about part1, if you don't need it, you don't need it. It's common to call it "dummy" or "unused" to show that it's not used.

You CAN be ugly with:

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

In this specific case, but that's obfuscating and not nice towards others. ;)

I think a question I asked some time ago could help you:

Pythonic way to get some rows of a matrix

NumPy gives you the slice syntax you want to extract various elements using a tuple or list of indices, but I don't think you'd like to convert you list of strings to a numpy.array just to extract a few elements, so maybe you could write a helper:

def extract(lst, *indices):
    return [lst[i] for i in indices]

item0, item2 = extract(str.partition(' '), 0, 2)

you could also use str.split(' ', 1) instead of str.partition(' ')

you'll get back a list instead of a tuple, but you won't get the separator back

This is how I would do it:

all_parts = str.partition(' ')
part0, part2 = all_parts[0], all_parts[2]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top