Maintaining sequence type in set or list comprehension in python

By : tjm
Source: Stackoverflow.com
Question!

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

By : tjm


Answers

There is no common way to do this without type checking. Also for sets you can use a set comprehension: { p[prefixlen:] for p in seq }.

By : refaim


This video can help you solving your question :)
By: admin