Home > Software engineering >  How can I convert any nested lists to tuples?
How can I convert any nested lists to tuples?

Time:10-02

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",
        ),
    ),
)

CodePudding user response:

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

  • Related