moll koll
moll koll

Reputation: 25

How can I convert any nested lists to tuples?

Input:

(
    ("Alfred", ["gaming", "shopping", "sport", "travel"]),
    (
        "Carmen",
        [
            "cooking",
            "pets",
            "photography",
            "shopping",
            "sport",
        ],
    ),
)

How can I convert any list inside this list (or further depth) to a tuple?

Expected output:

(
    ("Alfred", ("gaming", "shopping", "sport", "travel")),
    (
        "Carmen",
        (
            "cooking",
            "pets",
            "photography",
            "shopping",
            "sport",
        ),
    ),
)

Upvotes: 0

Views: 53

Answers (1)

rkechols
rkechols

Reputation: 577

I'm going to assume your original data is in a variable named t

t = tuple((item[0], tuple(item[1])) for item in t)

This uses tuple() to convert the list (or any iterable) into a tuple.

Docs: https://docs.python.org/3.3/library/stdtypes.html?highlight=tuple#tuple

Upvotes: 1

Related Questions