If I have a function that can operate on both sets and lists and should return a modified form of the sequence, is there a way to preserve the sequence type but still use a comprehension? For example, in the following if I call stripcommonpathprefix with a set, it works but has the undesired side effect of converting the set to a list. Is it possible to maintain the type (while still using a comprehension) without having to directly check isinstance and then return the correct type based on that? If not, what would be the cleanest way to do this?
def commonpathprefix(seq):
return os.path.commonprefix(seq).rpartition(os.path.sep)[0] + os.path.sep
def stripcommonpathprefix(seq):
prefix = commonpathprefix(seq)
prefixlen = len(prefix)
return prefix, [ p[prefixlen:] for p in seq ]
Thankyou and sorry if this is a basic question. I’m just starting to learn python.
P.S. I’m using Python 3.2.2
There is no good way to preserve the type of the sequence. As you have guessed, if you really want to do this, you will have to convert the answer at the end to the type you want. It’s quite likely that you don’t need to do this, so you should think hard about it.
One shortcut that might help you if you do decide to convert: the types of the built-in sequences are also constructors that can create those sequences: