List to Tuple and Tuple to List?

Paul Hankin paul.hankin at gmail.com
Tue Nov 6 06:54:21 EST 2007


On Nov 6, 11:18 am, Davy <zhushe... at gmail.com> wrote:
> Hi all,
>
> I am curious about whether there is function to fransform pure List to
> pure Tuple and pure Tuple to pure List?
>
> For example,
>
> I have list L = [[1,2,3],[4,5,6]]
> something list2tuple() will have T=list2tuple(L)=((1,2,3),(4,5,6))
>
> And the tuple2list()

Assuming you only want to look inside the types that you're
replacing...

def transform(source, from_type, to_type):
    if not isinstance(source, from_type):
        return source
    else:
        return to_type(transform(x, from_type, to_type)
            for x in source)

def list2tuple(source):
    return transform(source, list, tuple)

def tuple2list(source):
    return transform(source, tuple, list)

--
Paul Hankin





More information about the Python-list mailing list